Understanding the use of this in JavaScript and call(apply)
This article sorts out what this refers to in object methods, ordinary functions, and constructor functions in JavaScript, and explains how call and apply change the execution context.
To gain a deeper understanding of the JavaScript language, one essential concept you must master is
this . Among these, call and apply are also this closely related. Now that I have some free time, after watching some tutorials online, I've organized them in this blog post based on my impressions.To gain a deeper understanding of the JavaScript language, one essential concept you must master is
this . Among these, call and apply are also this closely related. Now that I have some free time, after watching some tutorials online, I've organized them in this blog post based on my impressions.What is this
this is a keyword in JavaScript. It is used in object methods. this always points to the object that calls the method. Let's look at a simple example:When this is in an object method
var obj = {
name : 'object',
sayName : function () {
alert(this.name);
}
};
obj.sayName(); // objectIt can be seen that when the object
obj calls sayName this method,this points to obj . Therefore, alert(this.name) the result will be object. That is, when this appears in an object method, when the method is executed this points to the object itself.Let's look at another example.
When this is inside a function
var test = function () {
this.message = 1;
}
test();
alert(window.message); //1It can be seen that when a function is called directly, the function's internal
this points to the global object. In this example, the global object is window , which means this example is in a browser. By slightly modifying the example, it can be seen more intuitively that this points to the global object.var message = "hi";
var test = function () {
alert(this.message);
}
test(); // hiThe above example shows that when a function is called directly, the function's internal
this always points to the global object. Next, let's look at what this points to in a constructor.When this is inside a constructor
var name = "global";
function Person () {
this.name = "someone";
}
var sam = new Person();
alert(sam.name); // someoneThe above code clearly demonstrates what
this points to in a constructor. When an instance of a constructor is declared, the constructor's internal this all point to the new instance. Therefore, when executing var sam = new Person() this statement, this points to sam , so at this point sam.name = "someone"。this The positions where it appears are roughly the above cases. In addition, JavaScript's call and apply methods are also closely related to this are closely related. Next, let's look at call and apply the situation.What are call and apply
call The method is applied to Function object. The syntax iscall([thisObj[,arg1[, arg2[, [,.argN]]]]])| Parameters | Explanation |
|---|---|
| `thisObj` | Optional. The object to be used as the current object. |
| `arg1, arg2, , argN` | Optional. The sequence of method parameters to be passed. |
Explanation:The call method can be used to call a method on behalf of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj. If the thisObj parameter is not provided, then the Global object is used as thisObj.
Apply and Call are the same in effect, but they differ in their parameters. The meaning of the first parameter is the same for both, but for the second parameter: apply takes in an array of parameters, that is, multiple parameters are combined into an array and passed in, whereas call passes them as the parameters of call (starting from the second parameter). For example,
func.call(func1,var1,var2,var3)The corresponding apply form is:func.apply(func1,[var1,var2,var3]). This article uses `call` as an example.The text above should be quite easy to understand. But to truly master it,
call you still have to study it carefully. Let's look at an example:Passing an object to call
var sayName = function () {
alert(this.name);
}
var peter = {
name: "peter"
}
sayName.call(peter); //peterThe example above allows for a very intuitive understanding of
call how it works. That is to say, when calling within a function call this method, the function's internal this object will automatically point to call the first parameter in the method. In the example above, that is peter this object. So when executing sayName.call(peter) the function's internal this.name will automatically point to peter.name . Therefore, the final result is peter. This is a very easy-to-understand example. Next, let's look at a more complex case.function Person1 () {
this.name = "person1";
this.sayName = function () {
alert(this.name);
}
}
function Person2 () {
this.name = "person2";
}
var sam = new Person2();
Person1.call(sam);
sam.sayName(); //person1In the above example, the most critical part is
Person1.call(sam) this step. Let's see what actually happens inside. When calling callthis method, the function Person1 inside this points to sam this object. Equivalently, to sam this object, execute these two statements:this.name = "person1";
this.sayName = function () {
alert(this.name)
}Therefore, here the original
sam in the object name property is overridden. Moreover, a new method is obtained. So it can be successfully called sam.sayName() and the result returns person1 。pass the function into call
function class1 () {
this.message = "yeah";
}
function class2 () {
this.sayMessage = function () {
alert(this.message);
}
}
class2.call(class1);
alert(class1.sayMessage);
class1.sayMessage(); //undefinedIn the above example, we called
class2 of the function call method, passing in class1 this function. As a result, class1 has sayMessage this method. But the result returned by directly calling this method is undefined rather than what we expected yeah . Why is this? To figure out the this pointing here, we make the following modification:var message = "hi";
function class1 () {
this.message = "yeah";
}
function class2 () {
this.message = "hello";
this.sayMessage = function () {
alert(this.message);
}
}
class2.call(class1);
alert(class1.sayMessage);
class1.sayMessage(); // hello
class1.message = "msg";
class1.sayMessage(); //msgThe first call
sayMessage method, returns hello . Let's look again at class2.call(class1) this process. When this method is executed,class1 obtains class2 's message property and sayMessage method. So at this point there is class1.message = "hello" ,class1.sayMessage = function () {alert(this.message)}. Therefore, when executing sayMessage it returns hello. When we manually modify class1.message and then call this method again, the returned value is the value we modified. This proves that our reasoning above is correct.Let's look at the previous example again.
function class1 () {
this.message = "yeah";
}
function class2 () {
this.sayMessage = function () {
alert(this.message);
}
}
class2.call(class1);
alert(class1.sayMessage);
class1.sayMessage(); //undefinedIn this example, the
class1.message property is not defined. So when executing the sayMessage method, it returns undefined. One thing that is easy to confuse is that the class1defined in this.message is not class1.message . Rather, only class1 instances have this message property.There is another similar example below:
function Class1(){
this.showTxt = function(){alert(this.name)}
}
function Class2(){
this.name = 'class2';
}
var class1 = new Class1();
class1.showTxt.call(Class2);//undefined
alert(Class2.showTxt);//undefinedThe reason is the same as the example above.
Class2 does not define name this property.
