Return to ‘this’

As promised before that 3 day kata digression time to get back to ‘this’.  It may be better to consider what ‘this’ is NOT bound to.

 

var fn = function(a, b){

log(this);

}

var ob2 = {method:       fn};

…the function object this appears within

…”an instance of” the function this appears within (Generally true ie not bound)

…an object that happens to have that function as a property

var obj = {

fn : function(a, b){

log(this);

}

};

…the object created by the literal this appears within

var obj = {

fn : function(a, b){

log(this);

}

};

obj.fn(3, 4);

…an “execution context” or “scope” of that function call

So now we have seen what it’s not bound to, the question is what is ‘this’ bound to?

When there in a period to the left of a function innovation, i.e. it’s looked up as a property of an object on the LHS you can see what object was looked upon.  Put simply the object to the left of the period is what this references.

Once again consider obj.fn(a, b); this references obj

NOTE: when there is no . i.e. dot then it will be bound to the global scope.

The keyword this makes it possible to build just one function call and use it as a method on other objects.  When we call it, it has access to whatever object it is being called on.  This conserves memory.

All in all that was a bit harder than I expected but I did learn when there is a dot look to the left and that is what this is bound to.

 

Leave a Reply

Your email address will not be published. Required fields are marked *