You can use this to point to the newly created object when you create the constructor yourself in JavaScript. This prevents the this in the function from pointing to the global, as follows
var x = 2; function Test () { this. x = 1; } varnew//2
Conversely, if you do not use new, only the above function as a normal function to use, the internal function of this will point to the global object, as follows
var x = 1; function Test () { this. x = 0//0
Again, if the function that uses this is put into an object, this is bound to the current object, as follows
var x=3; var point = { 0, 0, function(x, y) { this. x + x; This this. Y + y; } ; Point.moveto (1, 1); alert (point.x) ; // 1alert (x); // 3
In conclusion, it looks like this inside the function will find the nearest outer object to bind, so I can't find the object to find the window.
However, the question comes, what if the function inside the function uses this? As follows:
varPoint ={x:0, y:0, MoveTo:function(x, y) {//intrinsic Functions varMoveX =function(x) { This. x = x;//this binds to the global }; //intrinsic Functions varMovey =function(y) { This. y = y;//this binds to the global }; MoveX (x); Movey (y); } }; Point.moveto (1, 1); Point.x; //==>0Point.y;//==>0X//==>1Y//==>1
This does not only not find the outer object point, but directly to the global variable, resulting in the generation of two global variables, good dangerous situation AH!!!
The workaround is to save this to a local variable inside the function, as follows
varPoint ={x:0, y:0, MoveTo:function(x, y) {varthat = This; //intrinsic Functions varMoveX =function(x) {that.x=x; }; //intrinsic Functions varMovey =function(y) {that.y=y; } moveX (x); Movey (y); } }; Point.moveto (1, 1); Point.x; //==>1Point.y;//==>1
So no two brushes really do not want to use this,
Later, ES6, known as the next generation of JavaScript, gave an arrow function "= =".
Look at the introduction and use of arrows, it seems that it is a function of shorthand, anyway, look at the special not accustomed to, awkward!
For example, the following simple arrow function code:
(A, b) = + A + b
At first glance, this is an expression, right? Where does it look like a function? I am impatient, who is full of support to come up with this shorthand way ...
Until later, at the bottom of the introduction, an "This of an arrow function always points to the function definition,"
That is, the "this" in the arrow function will no longer change, even if the two-bit call and apply do not alter this fact
var x = 1, = { ten, this. x };alert (o.x); // Ten // 1 // It's still 1 .
This will not change the pointer to the object's
JS Daily notes of this