Skip to content

Instantly share code, notes, and snippets.

@BrunoCaimar
Created October 8, 2015 19:12
Show Gist options
  • Save BrunoCaimar/e1bbccaed74a5e02a6bd to your computer and use it in GitHub Desktop.
Save BrunoCaimar/e1bbccaed74a5e02a6bd to your computer and use it in GitHub Desktop.
Javascript Stuff

The first common temptation is to assume this refers to the function itself. That's a reasonable grammatical inference, at least.

The next most common misconception about the meaning of this is that it somehow refers to the function's scope. It's a tricky question, because in one sense there is some truth, but in the other sense, it's quite misguided.

We said earlier that this is not an author-time binding but a runtime binding. It is contextual based on the conditions of the function's invocation. this binding has nothing to do with where a function is declared, but has instead everything to do with the manner in which the function is called.

this is actually a binding that is made when a function is invoked, and what it references is determined entirely by the call-site where the function is called.

function foo() { console.log( this.a ); }

var obj = { a: 2, foo: foo };

var bar = obj.foo; // function reference/alias!

var a = "oops, global"; // a also property on global object

bar(); // "oops, global"

Even though bar appears to be a reference to obj.foo, in fact, it's really just another reference to foo itself. Moreover, the call-site is what matters, and the call-site is bar(), which is a plain, un-decorated call and thus the default binding applies.

Is the function called with new (new binding)? If so, this is the newly constructed object.

var bar = new foo()

Is the function called with call or apply (explicit binding), even hidden inside a bind hard binding? If so, this is the explicitly specified object.

var bar = foo.call( obj2 )

Is the function called with a context (implicit binding), otherwise known as an owning or containing object? If so, this is that context object.

var bar = obj1.foo()

Otherwise, default the this (default binding). If in strict mode, pick undefined, otherwise pick the global object.

var bar = foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment