JavaScript this can be bound to: global objects, their own defined objects, objects generated with constructors, change bound objects by call or apply
1. Global Objects
function Globaltest (name) { this.name=name;} globaltest (' tree '); Console.log (name);//tree, the global object name is generated by default, This is generally not allowed.
2. The object of your own definition
var subway={ name:' line Line 1 ', speed :0, run:function( Speed) { the speed= speed; }}; Subway.run 100,this binding to an object subway
3. Objects generated with constructors
constructor conventions The first letter is capitalized, only the constructor is called with new, otherwise it is no different from the normal function, the constructor is called with new, and this binds to the generated object.
function Subway (speed) { this. speed=var s=new Subway; console.log (s.speed); // 100;this binding to a newly generated object
4. The specified object, via call or Apply binding
The difference between the call function and the Apply function is that the parameters are different, and two methods can change the object of this binding, as follows
Call (Obj,param1,param2 ...) ;
apply (obj,[]/*params[] parameter array */);
functionSubway (name) { This. name=name; This. speed=0; This. run=function(speed) { This. speed=Speed ; }; } vars=NewSubway (' line Line 1 ')); S.run (300); Console.log (' One line speed: ', s.speed);//300;this binding to the newly generated object s vars1=NewSubway (' line Line 2 ')); S.run.apply (s1,[100]); Console.log (' Line Line 2 speed: ', s1.speed);//100;this binding to an object S1S.run.call (s1,200); Console.log (' Line Line 2 speed: ', s1.speed);//200;this binding to an object S1
At last:
JavaScript has a design flaw that makes the this binding confusing
varsubway={name:' Line Line 1 ', Speed:0, run:function(speed) { This. speed=speed;//binding to the object itself functionTest (speed) { This. speed=speed+50;//It's weird to be bound to a global variable.} test (speed); } }; Subway.run (100); Console.log (subway.speed);// -Console.log (speed);// Max
Workaround Conventions Replace this with that
var subway={ name:' line Line 1 ', speed :0, run:function( Speed) { var that=this; // Replace this with that this. speed= speed; function Test (speed) { that.speed=speed+50; } Test (speed); } }; Subway.run (+); Console.log (subway.speed); // Max
Javascript-this Understanding