Home  >  Article  >  Web Front-end  >  Detailed explanation of the functions of call and apply keywords in js

Detailed explanation of the functions of call and apply keywords in js

高洛峰
高洛峰Original
2016-12-06 11:05:45899browse

The role of javascript call and apply keywords

apply accepts two parameters. The first parameter specifies the pointer to the this object in the function body, and the second parameter is a collection with subscripts.

call is syntactic sugar for apply. If the number of parameters is fixed, you can pass the second parameter without subscripting the set.

var func = function(a,b,c)
{
 alert(a + b + c);
}
func.apply(null,[1,2,3]);//弹出6
func.call(null,1,2,3);//弹出6

When the first parameter passed in apply and call is null, this in the function body will point to window.

When the first parameter passed in apply and call is null, this in the function body will point to window.

Uses of call and apply

1. Change the pointing of this

var obj1 = {
 name = '刘备'
}
  
var obj2 = {
 name = '曹操'
}
var getName = function(){
 alert(this.name);
}
  
window.name = '三国';
getName();//弹出"三国"
getName.call(obj1);//弹出"刘备"
getName.call(obj2);//弹出"曹操"

So, when this is inexplicably changed in some cases, you can use call or apply to correct the pointing of this.

document.getElementById('div1').onclick = function(){
 alert(this.id);//div1
 var fun1 = function(){
  alert(this.id);//window.id 即undefined
 }
 fun1();//普通函数的方式调用,this指代window,相当于window.id 即 undefined
}

Since it is called as a normal function, in the above example, this has become window. Let's see how to use call to make corrections.

document.getElementById('div1').onclick = function(){
 alert(this.id);
 var fun1 = function(){
  alert(this.id);
 }
 fun1.call(this);//强制函数内的this为外层的this,
}

2. Calling functions of other objects

Example 1:

var obj1 = {
 a:1,
 b:2,
 add:function()
 {
  return this.a + this.b;
 }
}
var obj2 = {
 a:1,
 b:2,
}
var result = obj1.add.call(obj2);//用obj1的函数来计算obj2的两个属性的和
alert(result);//输出3

Example 2: Borrowing constructors to achieve inheritance-like effects

var A = function(name)
{
 this.name = name;
};
var B = function(){
 A.apply(this,arguments)
}
B.prototype.getName = function(){
 return this.name;
}
var b = new B('刘备');
alert(b.getName());


Statement:
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