1. This in the global code is a pointer to the global object, which is the window in the browser
Alert (this) //window
2, as a simple function call:
function Foocoder (x) { this. x= x; } Foocoder (2); alert (x); //
This in the normal function, which points to the global function, window, in strict mode, is undefined
3. Method invocation as an object:
var " Clever Coder " ; var person = { "foocoder", hello:function (sth) { Console.log (this" + sth);} } Person.hello ("helloworld"
Output foocoder says Hello world. This points to the person object, which is the current object.
4. As a constructor:
New
This inside the function points to the newly created object
5. Internal function
varName ="Clever Coder"; varperson ={name:"Foocoder", Hello:function (sth) {varSayHello =function (sth) {Console.log ( This. Name +"says"+sth); }; SayHello (STH); }} Person.hello ("Hello World");//clever coder says hello world
In an intrinsic function, this is not bound to the outer function object as expected, but is bound to the global object. This is generally considered a design error in JavaScript because no one wants the this in the inner function to point to the global object. The general process is to save this as a variable, which is generally agreed to that or self:
varName ="Clever Coder"; varperson ={name:"Foocoder", Hello:function (sth) {varthat = This; varSayHello =function (sth) {Console.log (That.name+"says"+sth); }; SayHello (STH); }} Person.hello ("Hello World");//foocoder says hello world
6. Use apply and call to set this
" World ")
Apply and call are similar, except that the arguments that follow are passed in through an array instead of being passed in separately. The method definition for both:
Call (Thisarg [, ARG1,ARG2, ...]); // parameter list, arg1,arg2, ... Apply (Thisarg [, Argarray]); //
Both are used to bind a function to a specific object, and this will naturally be set to the first parameter explicitly.
Summarize this:
1. When the function is called as a method of an object, this points to the object.
2. When the function is called as a fade function, this points to the global object (when strict mode is undefined)
3. This in the constructor points to the newly created object
4. This in the nested function does not inherit this from the upper function, and if necessary, it can be saved with a variable.
To summarize the simple point, if this is used in the function, it points to the object only if the function is called directly by an object.
- Obj.foocoder ();
- Foocoder.call (obj, ...);
- Foocoder.apply (obj, ...);
Original address: Http://www.cnblogs.com/aaronjs/archive/2011/09/02/2164009.html#_h1_6
What does the this in
JS do?