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 the object specified for the method call in Rule 1this pointer by default, for example, obj. fun (). The this pointer in the fun method body points to obj. 1 varuser {... SyntaxHighlighter. all ();
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 the object specified for the method call in Rule 1this pointer by default, for example, obj. fun (). The this pointer in the fun method body points to obj.
1 var user = {name: 'duan Guangwei '};
2 user. getName = function () {return this. name ;};
3 user. getName (); // return 'duan Guangwei'
1 var user = {name: 'duan Guangwei '};
2 user. getName = function () {return this. name ;};
3 user. getName (); // return 'duan Guangwei'
4
5 window. name = 'Li yunniu ';
6 window. getName = user. getName
7 window. getName (); // return 'Li yunniu'
8 getName (); // return 'Li yunniu 'rule 2. If no object is specified for the method during method calling, this Pointer Points to window by default, for example, fun (), the this pointer in the fun method body points to the window.
1 var fun = function (){
2 return this;
3}
4 fun (); // return window object rule 3 code not in the method body can be seen as being executed in an anonymous method. According to Rule 2, this pointer can be inferred to window.
1 this // window object changes the default point of this pointer to use apply1 var user = {name: 'duan Guangwei '};
2 user. hi = function (message) {return this. name + ':' + message ;};
3 window. name = 'Li yunniu'
4 user. hi (' '); // output 'duan Guangwei:'
5 user. hi. apply (window, [' ']); // output 'Li yunniu: 'using call1 var user = {name: 'duan Guangwei '};
2 user. hi = function (message) {return this. name + ':' + message ;};
3 window. name = 'Li yunniu'
4 user. hi (' '); // output 'duan Guangwei:'
5 user. hi. call (window, ''); // output 'Lee Niu:' this In the constructor points to this pointer in the constructor by default to the object being constructed.
1 var User = function (name ){
2 this. name = name;
3 };
4 User. prototype. hi = function (){
5 return this. name;
6 };
7 var user = new User ('duan Guangwei ');
8 user. hi (); // output 'duan guangwei' the last small test to guess what is the last output?
1 var User = function (name ){
2 this. name = name;
3 };
4 User. prototype. hi = function (){
5 return this. name;
6 };
7 var user = new User ('duan Guangwei ');
8 user. hi (); // output 'duan Guangwei'
9
10 var hi = user. hi;
11
12 hi (); // guess the output object expression. method (); will be translated as object expression. method. call (object expression );. Var temp = object expression. method; temp (); is translated as var temp = object expression. method; temp. call (window ).