A lot of people know this pointer, the main purpose of this article is to train our new company.
The default this pointer points to
Rule 1
The this pointer defaults to the object that was specified for the method call, such as: Obj.fun (), and the this pointer in the fun method body points to obj.
Copy Code code as follows:
var user = {name: ' De Guangwei '};
User.getname = function () {return this.name;};
User.getname (); Return to ' De Guangwei '
Copy Code code as follows:
var user = {name: ' De Guangwei '};
User.getname = function () {return this.name;};
User.getname (); Return to ' De Guangwei '
Window.name = ' Li Yu girl ';
Window.getname = User.getname
Window.getname (); Return to ' Li Yu chick '
GetName (); Return to ' Li Yu chick '
Rule 2
If an object is not specified for a method at the method call, the this pointer defaults to window, such as fun (), and the this pointer in the fun method body points to window.
Copy Code code as follows:
var fun = function () {
return this;
}
Fun (); Return Window Object
Rule 3 No code in the method body can be regarded as executing in an anonymous method, and according to rule 2 you can infer that the this pointer points to window.
This//window object
Change the this pointer's default point
Use Apply
Copy Code code as follows:
var user = {name: ' De Guangwei '};
user.hi= function (message) {return this.name+ ': ' +message;};
Window.name = ' Li Yu girl '
User.hi (' Hello '); Output ' De Guangwei: Hello '
user.hi.apply (window, [' Hello ']); Output ' Li Yu girl: Hello '
Using call
Copy Code code as follows:
var user = {name: ' De Guangwei '};
user.hi= function (message) {return this.name+ ': ' +message;};
Window.name = ' Li Yu girl '
User.hi (' Hello '); Output ' De Guangwei: Hello '
User.hi.call (window, ' hello '); Output ' Li Yu girl: Hello '
This point in the constructor
The this pointer in the constructor defaults to the execution of the object being constructed.
Copy Code code as follows:
var User = function (name) {
THIS.name = name;
};
User.prototype.hi = function () {
return this.name;
};
var user = new User (' De Guangwei ');
User.hi (); Output ' De Guangwei '
the final little test
Guess what the final output is?
Copy Code code as follows:
var User = function (name) {
THIS.name = name;
};
User.prototype.hi = function () {
return this.name;
};
var user = new User (' De Guangwei ');
User.hi (); Output ' De Guangwei '
var hi = user.hi;
Hi (); Guess the output here