Default bindings
// global objects for default bindings function foo () { Console.log (this. A)}var a=2; foo (); // 2
// function foo () { ' use strict ' ; Console.log ( this .a)} var a=2;foo (); // typeerror:this is undefined
// using foo () in strict mode does not affect the default binding function foo () { Console.log (this. A)}var a=2;(function() { ' use strict '; Foo ();}) (); // 2
Implicit binding
// When a function has a context object, An implicit binding rule binds this in a function call to this context object function Foo () {console.log ( this .a)} var obj={A: 2, Foo: Foo}obj.foo (); // 2
// Only the previous or last layer in the object's property chain functions in the calling position function foo () {console.log ( this .a)} var Obj2={A: 42 var obj1={A: 2, Obj2:obj2}obj1.obj2.foo () ; // 42
// this a function that is implicitly bound loses the bound object, which means that the default binding is applied. This binds this to the global object or to the undefined function foo ( {Console.log ( this .a)} var obj={A: 2, Foo: Foo} var bar=obj.foo; var a= "Hello" ;bar (); // hello
// parameter passing is actually implicitly passed, so we pass in the function is also implicitly assigned the value Span style= "COLOR: #0000ff" >function foo () {console.log ( this .a)} function Dofoo (FN) {fn ();} var obj={A: 2 var bar=obj.foo; var a= "Hello" ;d Ofoo (obj.foo) // hello
// callback function missing this binding function foo () { Console.log (this. A)}var obj={ A:2, var a= "Hello"; SetTimeout (Obj.foo,+) //Hello
Explicit binding
// by Foo.call (..), forcing its this to be bound to obj when calling Foo function foo () {Console.log ( this .a)} var obj={A: 2}foo.call (obj) // 2
// Hard Binding function foo () { Console.log (this. A)}var obj={ A:2 var bar=function() { //2setTimeout (bar,100); // 2 // hard-bound bar can no longer modify its this//2
//Hard Binding Typical scenario: Create a package function that takes care of receiving parameters and returning valuesfunctionfoo (something) {Console.log ( This. a,something); return This. A +something;}varobj={A:2}varBar=function(){ returnfoo.apply (obj,arguments)}varB=bar (3);//2 3Console.log (b)//5
//Hard Binding Typical scenario: Create an auxiliary function that can be reusedfunctionfoo (something) {Console.log ( This. a,something); return This. A +something;} //Simple Auxiliary binding functionfunctionbind (fn,obj) {return function(){ returnfn.apply (obj,arguments)}}varobj={A:2}varBar=bind (foo,obj);varB=bar (3);//2 3Console.log (b)//5
"You do not know the JS"--this comprehensive analysis