What could be causing the context of 'this' in Javascript to remain unchanged in this particular scenario?

Currently, I am exploring the concept of 'this' in Javascript and have encountered a perplexing situation.

After delving into how JavaScript functions operate as outlined here, I grasped that when a function is invoked on an object, the object is implicitly passed in as the first parameter (or explicitly when using the call method).

However, there were two cases that I attempted to test which did not yield the results I anticipated. Kindly review the two lines following //Why doesn't this work? Why are the following two values undefined?

You can find the code in a jsFiddle (also provided below)

function Beta(c, myValParam) {
  var callback = c;
  this.myVal = myValParam;
  this.RunCallback = function () {
   callback();
  }

  this.ShowVal = function () {
    alert("FROM Beta: " + this.myVal);
  }
}

function Alpha() {
  this.myVal = "Alpha's Property";
  this.ShowVal = function () {
    alert("FROM Alpha: " + this.myVal);
  }
}
a = new Alpha();
a.ShowVal();

b = new Beta(a.ShowVal, "Beta's property passed in");
b.ShowVal();

//Why doesn't this work? Why are the following two values undefined?
b.RunCallback.call(b); //Shouldn't this display the value in b?
b.RunCallback();

b2 = new Beta(function() { return a.ShowVal.call(a); }, "Z");
b2.RunCallback();

UPDATE: Following insights from Quentin, dystroy, and dough, I have made some changes in the updated jsFiddle to demonstrate the values produced when the context reverts to the window object

Additionally, here is the revised code with the call to callback.call(this) which resolves the issue I was facing

Answer ā„–1

Is it expected to showcase the value stored in variable b?

In this scenario, a function is being invoked with reference to variable b but doesn't interact with 'this'. This particular function also triggers the execution of 'callback' (which is essentially a clone of 'a.showVal') within the global context of 'window'.

Answer ā„–2

Don't overlook this important detail when defining RunCallback:

Make sure to make the following substitution:

callback();

to

callback.call(this);

Answer ā„–3

It seems like the problem arises when you execute callback without providing a context, causing the loss of this. One possible solution is to modify RunCallback as follows:

  this.RunCallback = function () {
   callback.call(this);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Evaluating manually bootstrapped AngularJS applications

I've encountered an issue while testing an AngularJS application (using Karma and Jasmine) where I manually bootstrap the application in the code after some HTTP AJAX requests. angular.module("app", []); angular.element(document).ready(function() { ...

The canvas is being expanded by utilizing the drawImage method

Ensuring the correct size of a <canvas> element is crucial to prevent stretching, which can be achieved by setting the width and height attributes. Without any CSS applied other than background-color, I am faced with an unusual issue. Using ctx.draw ...

I am having trouble with the browser detection not accurately identifying the browser I am currently using

Currently, I am working on a JavaScript code that will simply display the name of the browser being used to view the web page. Despite me using Safari, none of the navigators seem to recognize it as the current browser. The information displayed in my brow ...

Migrate the JavaScript variable created with 'passport' to an Express router

In my quest for authentication, I created the essential passportAuth.js file: module.exports = function(passport, FacebookStrategy, config, mongoose, fbgraph){ passport.serializeUser(function(user,done){ //to make user reference available across pages ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

The retrieved information remains unchanged even after modifications are made on the subsequent Next.js server-side rendered page

I'm facing an interesting scenario with my application. It consists of two main pages - one displaying user account statistics and the other allowing users to edit these statistics. Both pages are rendered on the server side. When I navigate to the fi ...

Determining if a component is nested within itself in Angular 6 is a crucial task

My goal is to develop a custom Angular component for a nested navigation menu with multiple levels. Below is an example of how the menu structure looks: app.component.html <nav-menu> <nav-menu-item>Section 1</nav-menu-item> <nav- ...

Encountering a Typescript error while attempting to iterate through Enum keys for generating JSX components

I'm really struggling with this problem. Here's a simple enum I have: export enum depositTypes { ACH = 42, Wire = 36, Check = 3, Credit = 2, } I'm trying to create option tags for a select element, like so: Object.keys(depositTyp ...

Developing a custom function to retrieve an array as a callback

I'm currently diving into the world of Node.js Struggling with implementing my own callback function in a certain method. It may seem like a straightforward task, but I'm finding it quite challenging to grasp. This specific function takes an ad ...

Conceal the Div containing the specified class

I was hoping to hide the first DIV if the second DIV is displayed on the front end, and vice versa upon page load. If the first DIV is set to 'block,' then the second DIV should be set to 'none.' And If the second DIV is set to &apos ...

Struggling to receive accurate data from every statement

I have an object (known as allUserInfo) that looks like this: Object { available_client_ids: Array[2] 0: "demo" 1: "4532t78" available_client_names: Array[2] 0: "Demo" 1: "Bobs Bakery" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Having trouble with submitting the code - need help resolving the issue

I'm facing an issue with my submit cancel code. The JavaScript code I implemented for preventing the submission function on my page isn't working as expected. While it does work to a certain extent, it's not fully functional. I am seeking a ...

Error message: "PHP encounters an issue with jQuery due to absence of 'Access-Control-Allow-Origin' header"

I am currently attempting to make an external API call in PHP using AJAX and jQuery, but I keep encountering the error message saying "No 'Access-Control-Allow-Origin' header is present". The API does not support JSONP. Is there any workaround t ...

Dynamically validate AngularJS forms with JSON Schema

I am currently trying to dynamically validate JSON in AngularJS. Unfortunately, I have encountered an issue with loading fields from the schema onto the page. My understanding of AngularJS is limited as I am still new to it. Although I have managed to cr ...

Leveraging ng-model with expressions in ng-repeat in AngularJS.Would you

Currently, I am tasked with creating a form for a multilanguage content management system using angularJS. The language list has been defined within the angular scope as follows: $scope.languages = [ {id:0,'name':'English'}, {id:1, ...

Exploring the intricacies of defining Vue component props in TypeScript using Vue.extend()

Here is a simple example to illustrate my question When I directly define my props inside the component, everything works fine <script lang="ts"> import Vue, { PropType } from "vue"; export default Vue.extend({ props: { col ...

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

Div keydown event not being triggered in Vue

I've been struggling to get my event to fire despite following the instructions in the title. @keydown="keyPressed($event)" Although currently it looks like this, I have also attempted setting the tabIndex and adding it on mount as shown be ...

Ways to transform a PHP function into one that can be invoked using Ajax

In my current project, Iā€™m facing an issue where I need to call multiple PHP functions that output HTML using Ajax. Instead of directly trying to call a PHP function with Javascript, I believe application routing can help the frontend hit the correct fun ...