JavaScript - mystery around `this` keyword -


as per understanding, if 'this' keyword used in function, refers owner of function. in following scenario why 'this' not able find object property of 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 'callingobj' , 'callingobj' has 'objectproperty' property. why 'this' not able recognize it?

in javascript function doesn't have specific owner. 1 object or several objects can have reference function, or no object @ all.

the value of this inside function depends on how call function. if use period syntax call it, or use call method or apply method, value of this object specify.

example:

someobj.func(); // using period syntax value 'this' someobj  func.call(someobj); // providing value 'this' 

when use period syntax without calling function, reference function, , it's not attached object. calling function using reference not provide value this, value global context, i.e. window object if code runs in browser.

example:

var f = someobj.func; // reference  f(); // call function without value 'this'  f.call(someobj); // call function specifying value 'this' 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -