Many people know this pointer. The main purpose of this article is to train new people in our company.
The default this pointer points to
Rule 1
This pointer points to the object specified when the method is called by default, such as: obj.fun(), the this pointer in the fun method body Point to obj.
var user = { name: 'Duan Guangwei' };
user.getName = function(){ return this.name; };
user.getName(); //Return 'Duan Guangwei'
var user = { name: 'Duan Guangwei' };
user.getName = function(){ return this .name; };
user.getName(); //Return 'Duan Guangwei'
window.name = 'Li Niuniu';
window.getName = user.getName
window. getName(); //Return '李妞妞'
getName(); //Return '李妞妞'
Rule 2
If during method call If no object is specified for the method, the this pointer points to window by default, such as: fun(), the this pointer in the fun method body points to window.
var fun = function(){
return this ;
}
fun(); //Return window object
Rule 3 Code that is not in the method body can be regarded as being executed in an anonymous method. According to Rule 2, it can be deduced Its this pointer points to window.
this //window object
Change the default pointer of this pointer
Use apply
var user = { name: 'Duan Guangwei' };
user.hi= function(message){ return this.name ':' message; };
window.name = 'Li Niuniu'
user.hi('Hello'); //Output 'Duan Guangwei: Hello'
user.hi.apply(window, ['Hello']); //Output' Li Nuuniu: Hello'
Use call
var user = { name: 'Duan Guangwei' };
user.hi= function(message){ return this.name ':' message; };
window.name = 'Li Niuniu'
user.hi('Hello'); //Output 'Duan Guangwei: Hello'
user.hi.call(window, 'Hello'); //Output 'Li Niuniu: Hello'
This pointer in the constructor points to
This pointer in the constructor points to the object being constructed by default.
var User = function(name){
this .name = name;
};
User.prototype.hi = function(){
return this.name;
};
var user = new User('Duan Guangwei');
user.hi(); //Output 'Duan Guangwei'
The last little test
Guess what the final output is?
var User = function(name){
this .name = name;
};
User.prototype.hi = function(){
return this.name;
};
var user = new User('Duan Guangwei');
user.hi(); //Output 'Duan Guangwei'
var hi = user.hi;
hi(); //Guess the output here