JavaScript中call()函数详细⽤法
call()⽅法调⽤⼀个函数, 其具有⼀个指定的this值和分别地提供的参数(参数的列表)。
注意:该⽅法的作⽤和⽅法类似,只有⼀个区别,就是call()⽅法接受的是若⼲个参数的列表,⽽apply()⽅法接受的是⼀个包含多个参数的数组。
语法
fun.call(thisArg, arg1, arg2, ...)
thisArg
在fun函数运⾏时指定的this值。需要注意的是,指定的this值并不⼀定是该函数执⾏时真正的this值,如果这个函数处于,则指定为null和undefined的this值会⾃动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的⾃动包装对象。
arg1, arg2, ...
指定的参数列表。
javascript全局数组
返回值
返回值是你调⽤的⽅法的返回值,若该⽅法没有返回值,则返回undefined。
描述
可以让call()中的对象调⽤当前对象所拥有的function。你可以使⽤call()来实现继承:写⼀个⽅法,然后让另外⼀个新的对象来继承它(⽽不是在新对象中再写⼀次这个⽅法)。
⽰例
在⼀个⼦构造函数中,你可以通过调⽤⽗构造函数的call⽅法来实现继承,类似于Java中的写法。下例中,使⽤Food和Toy构造函数创建的对象实例都会拥有在Product构造函数中添加的name属性和price属性,但category属性是在各⾃的构造函数中定义的。
function Product(name, price){
this.name = name;
this.price = price;
if(price <0){
throw RangeError(
'Cannot create product '+this.name +' with a negative price'
);
}
}
function Food(name, price){
Product.call(this, name, price);
this.category ='food';
}
//等同于
function Food(name, price){
this.name = name;
this.price = price;
if(price <0){
throw RangeError(
'Cannot create product '+this.name +' with a negative price'
);
}
this.category ='food';
}
//function Toy 同上
function Toy(name, price){
Product.call(this, name, price);
this.category ='toy';
}
var cheese =new Food('feta',5);
var fun =new Toy('robot',40);
在下例中的for循环体内,我们创建了⼀个匿名函数,然后通过调⽤该函数的call⽅法,将每个数组元素作为指定的this值执⾏了那个匿名函数。这个匿名函数的主要⽬的是给每个数组元素对象添加⼀个print⽅法,这个print⽅法可以打印出各元素在数组中的正确索引号。当然,这⾥不是必须得让数组元素作为this值传⼊那个匿名函数(普通参数就可以),⽬的是为了演⽰call的⽤法。
var animals =[
{species:'Lion', name:'King'},
{species:'Whale', name:'Fail'}
];
for(var i =0; i < animals.length; i++){
(function(i){
this.print =function(){
console.log('#'+ i  +' '+this.species +': '+this.name);
}
this.print();
}).call(animals[i], i);
}
在下⾯的例⼦中,当调⽤greet⽅法的时候,该⽅法的this值会绑定到i对象。
function greet(){
var reply =[this.person,'Is An Awesome',le].join(' ');
console.log(reply);
}
var i ={
person:'Douglas Crockford', role:'Javascript Developer'
};
greet.call(i);// Douglas Crockford Is An Awesome Javascript Developer

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。