var
is synonymous with global-object properties of the same name. They are not copies of each other but are each other. In default binding, this gets bound with the global scope. Note: Default binding is only applied when code is not executed in strict mode.function foo() {
console.log( this.a );
}
var a = 2;
foo(); // 2 ===> Default Binding
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
}
obj.foo(); // 2
And further note that only the top/last level of an object property reference chain matters to the call site.
function foo() {
console.log( this.a );
}
var obj2 = {
a: 42,
foo: foo
};
var obj1 = {
a: 2,
obj2: obj2
};
obj1.obj2.foo(); // 42
Sometimes implicitly bound functions lose the binding falling back to the default binding. This happens because in the below example obj.foo
is in fact a reference to foo
itself. Thus we are basically calling foo
with global scope binding.
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
}
var bar = obj.foo;
var a = "oops, global"; // `a` also property on global object
bar(); // "oops, global"
call(..)
and apply(..)
methods.function foo() {
console.log( this.a );
}
var obj = {
a: 2
}
// passing the object to be used for `*this*` explicitly
foo.call(obj); // 2
// foo.apply(obj); would behave the same
function foo(a) {
this.a = "hello";
this.b = "world";
}
var bar = new foo();
// `this` has been bound to bar here
console.log(bar.a); // hello
console.log(bar.b); // world
<aside> 👉🏼 Default Binding < Implicit Binding < Explicit Binding < new binding
</aside>
function foo() {
console.log(this.a);
}
var a = 2;
foo.call(null); // 2