Yash Garg
Yash Garg

Reputation: 3

JavaScript - mystery around `this` keyword

As per my understanding, if 'this' keyword is used in a function, then it always refers to the owner of the function. But in the following scenario why 'this' is not able to find the object property of the owner object -

var calledObj = {};
calledObj.objectProperty = 'calledObj property';
calledObj.calledMethod = function(){
  alert(this.objectProperty);
}

var callingObj = {
    objectProperty: 'callingObj property',
    callingMethod: function(callbackF){
        if(typeof callbackF !== 'function'){
          callbackF = false;
        }
        if(callbackF){              
          callbackF();
        }
    }
};
callingObj.callingMethod(calledObj.calledMethod); // alert 'UNDEFINED'

It should alert 'callingObj property', because 'callingMethod' belongs to 'callingObj' and 'callingObj' already has a 'objectProperty' property. Then why 'this' is not able to recognize it?

Upvotes: 0

Views: 78

Answers (2)

Guffa
Guffa

Reputation: 700322

In Javascript a function doesn't have a specific owner. One object or several objects can have a reference to the function, or no object at all.

The value of this inside the function depends only on how you call the function. If you use the period syntax to call it, or use the call method or apply method, the value of this is the object that you specify.

Example:

someObj.func(); // using period syntax the value for 'this' is someObj

func.call(someObj); // providing a value for 'this'

When you use the period syntax without calling the function, you just get the reference to the function, and it's not attached to the object. Calling the function using the reference will not provide a value for this, so the value will be the global context, i.e. the window object if the code runs in a browser.

Example:

var f = someObj.func; // get the reference

f(); // call the function without a value for 'this'

f.call(someObj); // call the function specifying a value for 'this'

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

this refers to the context, whatever that context may be.

As you write callbackF(), there is no context! You have dereferenced the function and therefore this is not what you expect.

callbackF.call(calledObj); will work, because this explicitly sets the context back to what you wanted it to be.

Upvotes: 3

Related Questions