There are many ways to bind this in JavaScript, which is summarized in the recent learning process, with default bindings, implicit bindings, display bindings, forced bindings, and instance bindings.
Next we look at:
Default bindings:
The code is as follows:
function foo () {
Console.log (THIS.A);
}
var a = 3;
Foo (); 3
Under global scope This is specified by default to window, and the default binding is how the call location determines the bound object of this.
Implicit binding:
function foo () {
Console.log (THIS.A);
}
var obj = {a:3, foo:foo};
Obj.foo (); 3
Implicit binding is easy to lose, such as
var Bar=obj.foo;
Bar ();//undefined
The call location is under window but the Foo method specifies obj as its binding object
Show Bindings:
function foo () {
Console.log (THIS.A);
}
var obj = {A:3};
Foo.call (obj); 3
Force this to be bound to obj when we invoke foo using call
Force binding:
function foo () {
Console.log (THIS.A);
}
var obj = {A:3};
var bar = function () {
Foo.call (obj);//Forced binding
};
Bar (); 3
SetTimeout (bar, 100); 3
A bar that is forced to bind can no longer modify its this
Bar.call (window); or 3?
Instance bindings:
JavaScript also has a new operator
function foo (a) {
THIS.A = A;
}
var bar = new Foo (3);
Console.log (BAR.A); 3
The binding of this in JavaScript