this keyword in Javascript
15 Dec 2016The following notes are a resummarization from Kyle Simpson as a note to myself
What is this? Every function, while executing, has a reference to its current execution context
What determines which object a functions this points to? What’s the default?
- Default and Implicit Binding rule
function foo() {
console.log(this.bar);
}
var bar = "bar1";
var o2 = { bar: "bar2", foo: foo };
var o3 = { bar: "bar3", foo: foo };
//the call below is a normal call and uses default binding
//in strict mode this will be undefined
//in non strict mode it wil be the global
foo(); //"bar1"
//below we illustrate implicit binding
//we make a reference to o2 as the owner or containing object
//and use it to call the function, 'this' now points to o2's 'this' context
o2.foo(); //"bar2"
o3.foo(); //"bar3"
- Using the
new
keyword
function foo() {
this.baz = "baz";
console.log(this.bar + " " + baz);
}
var baz = "bar";
// below we will get a brand new object with a new 'this' context
// also the object inherits from foo's prototype
// if there is no return statement, 'this' will be implicitly returned
var baz = new foo();
//the above will log "undefined bar"
//this is because this.bar is set on our new this context
- Explicit Binding with a call, apply or bind(as of ES5)
function foo(a,b) {
console.log(a + " " + b + " " + this.bar);
}
var bar = "bar1";
var obj = { bar: "bar2" };
foo(); // "bar1" due to default binding
//first argument is the owner object or 'this' context
foo.call(obj, "a", "b"); // "a b bar2" - explicitly use obj as this
foo.apply(obj, ["a", "b"]); // "a b bar2" - same except extra arguments in array
foo = foo.bind(obj, "a", "b");
foo(); // "a b bar2" - note we have to explicitly call foo after binding