Home > Web Front-end > JS Tutorial > body text

Javascript technical difficulties: the connection between apply, call and this_javascript skills

WBOY
Release: 2016-05-16 15:27:45
Original
1005 people have browsed it

1.apply definition

apply: Call the function, replace the this value of the function with the specified object, and replace the parameters of the function with the specified array.

Syntax: apply([thisObj[,argArray]])

thisObj

Optional. The object to use as this object.

argArray

Optional. A set of arguments to be passed to the function.

2.call definition

call: Call a method of an object and replace the current object with another object.

Syntax: call([thisObj[, arg1[, arg2[, [, argN]]]]])

thisObj

Optional. The object to be used as the current object.

arg1, arg2, , argN

Optional. The parameter list that will be passed to the method.

3. The difference between the two

The second parameter of call can be of any type, while the second parameter of apply must be an array or arguments.

The definitions are also different.

4. Example analysis

(1)Official example:

function callMe(arg1, arg2){
  var s = "";
  s += "this value: " + this;
  s += "<br />";
  for (i in callMe.arguments) {
    s += "arguments: " + callMe.arguments[i];
    s += "<br />";
  }
  return s;
}
document.write("Original function: <br/>");
document.write(callMe(1, 2));
document.write("<br/>");
document.write("Function called with apply: <br/>");
document.write(callMe.apply(3, [ 4, 5 ]));
document.write(callMe.call(3, 4, 5 ));
// Output: // Original function: // this value: [object Window] // arguments: 1 // arguments: 2 // Function called with apply: // this value: 3 // arguments: 4 // arguments: 5 
Copy after login

The first one uses apply: Definition: Call a function and replace the this value of the function with the specified object. Call the function callMe, and use the specified object 3 to replace this in the callMe function. At this time, this here is changed from the previous [object Window] becomes 3. The first one uses call: Definition: Call a method of an object and replace the current object with another object. Call the method of the object callMe and replace the object in callMe with another object 3. From the analysis of these results, it can be seen that both of them use the object in the specified object or the specified value to change this in the object. It can also be said that the object (this) in a function "hijacks" the object (this) in another function to be executed. In fact, this raises a question: What exactly is this? Why is it so important to go through so much trouble to change its direction again and again? Portal: Technical Difficulties of JavaScript (Part 3) - Detailed explanation of this, new, apply and call (the content here is great, definitely enough for you to drink a pot) (2) Example:

function zqz(a,b){
  return alert(a+b);
}
function zqz_1(a,b){
  zqz.apply(zqz_1,[a,b])
}
zqz_1(1,2)  //->3 
Copy after login

Analysis: According to the definition: call a function and replace the this value of the function with the specified object,

Here the function zqz is called and the this value of the zqz function is replaced with the specified object zqz_1.

Please note that the function name in js is actually an object, because the function name is a reference to the Function object!

function add(a, b)
{
 alert(a + b);
}
function sub(a, b)
{
 alert(a - b);
}
add.call(sub, 3, 1); // 4 
Copy after login

Analysis: According to the definition: Call a method of an object and replace the current object with another object.

Here is the method of calling the object add and replacing the current object sub with the add object;

Another example:

function zqz(a,b){
  this.name=a;
  this.age=b;
  alert(this.name+" "+this.age);
}
function zqz_1(a,b){
  zqz.apply(this,[a,b])   //我们亦可以这么写  zqz.apply(this,arguments) 
}
zqz_1("Nic",12)  //Nic 12 
Copy after login

Analysis: According to the definition: call a function and replace the this value of the function with the specified object,

The function zqz is called here, and the this of the function zqz is replaced with the specified object this.

Another example:

<input type="text" id="myText"  value="input text">
function Obj(){
  this.value="对象!";
}
var value="global 变量";
function Fun1(){
  alert(this.value);
}
Fun1();  //global 变量
Fun1.call(window); //global 变量
Fun1.call(document.getElementById('myText')); //input text
Fun1.call(new Obj());  //对象!
Fun1(); //global 变量 
Copy after login

分析:定义:调用一个对象的方法,用另一个对象替换当前对象。

调用Fun1对象的方法,用window对象替换当前Fun1中的对象。

调用Fun1对象的方法,用input中对象替换当前Fun1中的对象。

调用Fun1对象的方法,用新new出来的obj中的对象替换当前Fun1中的对象。

最后再总结一下:

如果在javascript语言里没有通过new(包括对象字面量定义)、call和apply改变函数的this指针,函数的this指针都是指向window的。

ps:apply的其他巧妙用法:

大家会不会觉得既然apply和call的用法差不多,那么为什么还同时存在这两种方法呢?完全可以丢掉一个呀。后来才发现一篇文章中讲到apply因为它所传参数为数组这一特点还有许多其他的妙用。

a) Math.max 可以实现得到数组中最大的一项:

因为Math.max 参数里面不支持Math.max([param1,param2]) 也就是数组,但是它支持Math.max(param1,param2,param3…),所以可以根据apply的特点来解决 var max=Math.max.apply(null,array),这样轻易的可以得到一个数组中最大的一项。(apply会将一个数组转换为一个参数接一个参数的传递给方法)

这块在调用的时候第一个参数给了一个null,这个是因为没有对象去调用这个方法,只需要用这个方法帮助运算,得到返回的结果就行,所以直接传递了一个null过去。

b) Math.min 可以实现得到数组中最小的一项:

同样和 max是一个思想 var min=Math.min.apply(null,array)。

c) Array.prototype.push 可以实现两个数组合并:

同样push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) 所以同样也可以通过apply来转换一下这个数组,即:

var arr1=new Array("1","2","3");
var arr2=new Array("4","5","6");
Array.prototype.push.apply(arr1,arr2); 
Copy after login

也可以这样理解,arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合。

d) 小结:通常在什么情况下,可以使用apply类似Math.min等之类的特殊用法:

一般在目标函数只需要n个参数列表,而不接收一个数组的形式([param1[,param2[,…[,paramN]]]]),可以通过apply的方式巧妙地解决这个问题。

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