A detailed description of this in JavaScript
The this in JavaScript is always confusing and should be one of JS's well known pits. Personally also think that JS in this is not a good design, due to this late binding characteristics, it can be a global object, the current object, or ... Some people even don't use this because of the big hole.
In fact, if you fully master this principle of work, nature will not enter these pits. Take a look at what this is pointing to in these cases:
1. This in the global Code
The This in the global scope will point to the global object, even if window is in the browser.
2. As a simple function call
123)45 |
function fooCoder(x) {this.x = x;}fooCoder(2);alert(x);// 全局变量x值为2
|
Here this points to the global object, which is window. In strict mode, it is undefined.
3. Method calls as objects
12345678 |
VarName="Clever coder";VarPerson={name : "Foocoder" ,hello : function (sth) {console log (this. Name + "says" + sth }}person hello ( "Hello World"
|
Output foocoder says Hello world. This points to the person object, which is the current object.
4. As a constructor
The This within the function points to the newly created object.
5. Intrinsic functions
123456789 |
VarName="Clever coder";VarPerson={Name:"Foocoder",Hello:function(Sth){VarSayHello=function (sth) { Console. Log (this. Name + "says" + sth }; sayhello (sth }}person . hello ( "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:
123456789 |
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"
|
6. Use call and apply to set this
1 |
person.hello.call(person, "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,… ] ); // 参数列表,arg1,arg2,...apply(thisArg [,argArray] ); // 参数数组,argArray
Both are used to bind a function to a specific object, and this will naturally be set to the first parameter explicitly.
Simply summarize
Simply summing up the above points, it can be found that only the 6th one is confusing.
In fact, you can summarize the following points:
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.
123 |
obj.foocoder();foocoder.call(obj, ...);foocoder.apply(obj, …);
|
Further
We may often write code like this:
1 |
$("#some-ele").click = obj.handler;
|
If This,this is used in handler, will it be bound to obj? Obviously not, after the assignment, the function is executed in the callback, and this is bound to the $ ("#some-div") element. This requires understanding the execution environment of the function. This article does not intend to elaborate on the execution environment of functions, but can refer to the implementation environment and scope chain in JavaScript advanced programming. To be pointed out here, understanding the execution environment of the JS function will better understand this.
So how can we solve the problem of callback function bindings? A new method has been introduced in ES5, bind ():
fun.bind(thisArg[, arg1[, arg2[, ...]]])thisArg当绑定函数被调用时,该参数会作为原函数运行时的this指向.当使用new 操作符调用绑定函数时,该参数无效.arg1, arg2, ...当绑定函数被调用时,这些参数加上绑定函数本身的参数会按照顺序作为原函数运行时的参数.
The method creates a new function, called a binding function, which is used as the first parameter of the Bind method when it is created, and the second and later parameters of the incoming bind method plus the parameters of the binding function itself are called in order as arguments to the original function.
Obviously the Bind method can solve the above problem well.
12 |
$("#some-ele").click(person.hello.bind(person));//相应元素被点击时,输出foocoder says hello world
|
In fact, the method is also very easy to simulate, we look at the Prototype.js bind method source code:
1234567 |
Function.Prototype.Bind=function(){ VarFn=This,Args=Array.Prototype.Slice.Pager(Arguments),Object= args. Shift(); return function() { return fn. Apply(object, args. Concat(Array. Prototype. Slice. Call(arguments)); }; };
|
Do you get it?
I believe after reading the full text, this is no longer a pit ~
Transferred from: http://foocoder.com/blog/xiang-jie-javascriptzhong-de-this.html/
A detailed description of this in JavaScript