Home > Web Front-end > JS Tutorial > In-depth understanding of the difference between apply() and call() methods in javascript_javascript skills

In-depth understanding of the difference between apply() and call() methods in javascript_javascript skills

WBOY
Release: 2016-05-16 15:05:51
Original
1287 people have browsed it

If you have never been exposed to dynamic languages, it will be a magical and weird feeling to understand JavaScript with the way of thinking of compiled languages, because things that are consciously impossible often happen, and even feel unreasonable. If you are learning When you encounter this feeling in the process of JavaScript, a free and ever-changing language, then from now on, please put down your "prejudice", because this is definitely a new continent for you, and let JavaScript slowly melt away from the past. Set a solidified programming consciousness and inject new vitality!

Okay, let’s get down to business. First, understand the dynamically changing runtime context characteristics of JavaScrtipt. This feature is mainly reflected in the use of the apply and call methods.

The difference between apply and call is just one sentence,

foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)


call and apply are both methods of Function.prototype, which are implemented internally by the JavaScript engine. Because they belong to Function.prototype, each Function object instance, that is, each method has call and apply attributes. Since they are attributes of the method , then their use is of course targeted at methods. These two methods are easy to confuse, because they have the same function, but they are used in different ways.

Same points: The two methods have exactly the same effect

Difference: The parameters passed by the method are different

Then what is the function of the method and what are the parameters passed by the method?

Let’s analyze the above foo.call(this, arg1, arg2, arg3).

foo is a method, this is the context-sensitive object when the method is executed, arg1, arg2, arg3 are the parameters passed to the foo method. The so-called context-sensitive objects when the method is executed here, if you have the basis of object-oriented programming, it is very It’s easy to understand, it’s this.

in the object after the class is instantiated.

In JavaScript, code always has a context object, and the code processes this object. The context object is represented by the this variable, and this this variable always points to the object where the current code is located.

In order to better understand what this is, let’s give an example.

/创建一个A类
function A(){
//类实例化时将运行以下代码
//此时的执行上下文对象就是this,就是当前实例对象
this.message = “message of a”;
this.getMessage = function(){
<SPAN style="WHITE-SPACE: pre">	</SPAN>return this.message;
<SPAN style="WHITE-SPACE: pre">	</SPAN>}
}
//创建一个A类实例对象
var a = new A();
//调用类实例getMessage方法获得message值
alert(a.getMessage());
//创建一个B类
function B(){
this.message = ”message of b”;
this.setMessage = function(msg){
<SPAN style="WHITE-SPACE: pre">	</SPAN>this.message = msg;
<SPAN style="WHITE-SPACE: pre">	</SPAN>}
}
//创建一个B类实例对象
var a = new B();
Copy after login

It can be seen that classes A and B both have a message attribute (a member in object-oriented terms). A has a getMessage method to get the message, and B has a setMessage method to set the message. The power of call is shown below.

//给对象a动态指派b的setMessage方法,注意,a本身是没有这方法的!
b.setMessage.call(a, “a的消息”);
//下面将显示”a的消息”
alert(a.getMessage());
//给对象b动态指派a的getMessage方法,注意,b本身也是没有这方法的!
Copy after login

This is the power of dynamic language JavaScript call!

It is simply "made out of nothing". The method of the object can be assigned arbitrarily, but the object itself has never had such a method. Note that it is assigned. In layman's terms, the method is lent to another object to complete the task. In principle The context object changes when the method is executed.

So b.setMessage.call(a, "a's message"); is equivalent to using a as the execution context object to call the setMessage method of the b object, and this process has nothing to do with b, and the effect is equivalent to a.setMessage(“a’s message”);

Because apply and call have the same effect, it can be said

The function of call and apply is to borrow other people’s methods to call, just like calling your own.

Okay, after understanding the similarities between call and apply--after their functions, let's take a look at their differences. After reading the above examples, I believe you probably know it.

From b.setMessage.call(a, "a's message") is equivalent to a.setMessage("a's message"), it can be seen that "a's message" is passed as a parameter in call,

So how does it express in apply? It’s not clear to explain directly. Apply needs to be combined with the application scenario to make it clear at a glance. Let’s design an application scenario:

function print(a, b, c, d){
alert(a + b + c + d);
}
function example(a, b , c , d){
//用call方式借用print,参数显式打散传递
print.call(this, a, b, c, d);
//用apply方式借用print, 参数作为一个数组传递,
//这里直接用JavaScript方法内本身有的arguments数组
print.apply(this, arguments);
//或者封装成数组
print.apply(this, [a, b, c, d]);
}
//下面将显示”背光脚本”
example(”背” , “光” , “脚”, “本”);
Copy after login

In this scenario, in the example method, a, b, c, d are used as parameters passed by the method. The methods use apply and call respectively to borrow the print method to call,

The last sentence is because the example method is called directly, so the context object this in this method is the window object.

So, except for the first parameter of the call and apply methods, which is the context object during execution, the other parameters of the call method will be passed to the borrowed method as parameters in turn, while apply has only two parameters, the second parameter Passed as an array. So it can be said as

The difference between the call and apply methods is that starting from the second parameter, the call method parameters will be passed to the borrowed method as parameters in turn, while apply directly puts these parameters into an array and then passes them, and finally the parameter list of the borrowed method It’s the same.


Application scenarios:

When the parameters are clear, you can use call. When the parameters are unclear, you can use apply to combine arguments

//例
print.call(window, “背” , “光” , “脚”, “本”);
//foo参数可能为多个
function foo(){
<SPAN style="WHITE-SPACE: pre">	</SPAN>print.apply(window, arguments);
}
Copy after login

The above article provides an in-depth understanding of the difference between the apply() and call() methods in JavaScript. This is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template