This article introduces you to the application of the Javascript knowledge point & quot; this pointer & quot; that you must know. Many people know this pointer for reference. The main purpose of this article is to train new people in our company.
The default this Pointer Points
Rule 1
By default, this pointer points to the object specified for a method call, such as obj. fun (). this Pointer Points to obj in the fun method body.
The Code is as follows:
Var user = {name: 'duan Guangwei '};
User. getName = function () {return this. name ;};
User. getName (); // return 'duan Guangwei'
The Code is as follows:
Var user = {name: 'duan Guangwei '};
User. getName = function () {return this. name ;};
User. getName (); // return 'duan Guangwei'
Window. name = 'Li yunniu ';
Window. getName = user. getName
Window. getName (); // return 'Li yunniu'
GetName (); // return 'Li yunniu'
Rule 2
If no object is specified for the method when calling the method, the this Pointer Points to window by default, for example, fun (). The this pointer in the fun method body points to window.
The Code is as follows:
Var fun = function (){
Return this;
}
Fun (); // return the window object
The code in rule 3 that is not in the method body can be considered to be executed in an anonymous method. According to Rule 2, it can be inferred that its this Pointer Points to window.
This // window object
Change the default value of this pointer.
Use apply
The Code is as follows:
Var user = {name: 'duan Guangwei '};
User. hi = function (message) {return this. name + ':' + message ;};
Window. name = 'Li yunniu'
User. hi (' '); // output 'duan Guangwei:'
User. hi. apply (window, [' ']); // output 'Li yunniu:'
Use call
The Code is as follows:
Var user = {name: 'duan Guangwei '};
User. hi = function (message) {return this. name + ':' + message ;};
Window. name = 'Li yunniu'
User. hi (' '); // output 'duan Guangwei:'
User. hi. call (window, ''); // output 'Li yunniu:'
This point in the constructor
The this pointer in the constructor points to the object being constructed by default.
The Code is as follows:
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'
Last small test
Guess the last output?
The Code is as follows:
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