kev*_*nji 77
您使用call或apply当您想要向this函数传递不同的值时.从本质上讲,这意味着您要执行一个函数,就好像它是特定对象的方法一样.两者之间的唯一区别是call期望参数用逗号分隔,同时apply期望数组中的参数.
Mozilla apply页面的一个例子,其中构造函数是链接的:
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.apply(this, arguments);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.apply(this, arguments);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
Run Code Online (Sandbox Code Playgroud)
什么Product.apply(this, arguments)所做的是以下内容:Product构造被施加为在每个的功能Food和Toy构造,并且每个这些对象实例的正与传递this.因此,每个Food和Toy现在都有this.name和this.category属性.
jfr*_*d00 10
您.call()希望使用不同的this值执行函数时使用.它将this值设置为指定值,将参数设置为指定,然后调用该函数..call()执行函数和执行函数之间的区别是this函数执行时指针的值.当你正常执行函数时,javascript决定this指针将是什么(通常是全局上下文,window除非函数被调用为对象上的方法).使用时.call(),您可以准确指定要this设置的内容.
您可以使用.apply(),当你想传递给函数的参数是一个数组. .apply()也可以使函数以特定this值执行. .apply()最常用的是当你有一些来自其他来源的不确定数量的参数时.通常使用通过使用特殊局部变量arguments将一个函数调用的参数传递给另一个函数,该变量包含传递给当前函数的参数数组.