任何人都可以解释在 Javascript 中使用的上下文call
和apply
方法吗?
为什么要使用call
andapply
而不是直接调用函数?
任何人都可以解释在 Javascript 中使用的上下文call
和apply
方法吗?
为什么要使用call
andapply
而不是直接调用函数?
当您想将不同的值传递给函数时,您会使用call
或。从本质上讲,这意味着您希望将函数作为特定对象的方法来执行。两者之间的唯一区别是期望参数以逗号分隔,而期望参数在数组中。apply
this
call
apply
Mozillaapply
页面的一个示例,其中构造函数被链接:
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);
什么Product.apply(this, arguments)
所做的是以下情况:该Product
构造函数被施加为在每个的功能Food
和Toy
构造,并且每个这些对象实例的正与传递this
。因此,每个Food
和Toy
现在都具有this.name
和this.category
属性。
您可以使用.call()
,当你想引起不同的执行函数this
值。它设置this
指定的值,设置指定的参数,然后调用函数。.call()
和只是执行函数的区别在于this
函数执行时指针的值。当您正常执行函数时,javascript 决定this
指针将是什么(通常是全局上下文,window
除非函数作为对象的方法被调用)。使用 时.call()
,您可以准确指定要this
设置的内容。
您可以使用.apply()
,当你想传递给函数的参数是一个数组。 .apply()
也可以使函数以特定this
值执行。 .apply()
当您有不确定数量的来自其他来源的参数时,最常使用。通过使用arguments
包含传递给当前函数的参数数组的特殊局部变量,它也经常用于将参数从一个函数调用传递到另一个函数调用。
如果您有使用 jQuery 的经验,您就会知道大多数函数都使用this
对象。例如,collection.each(function() { ... });
在这个函数内部,"this"
指的是迭代器对象。这是一种可能的用法。
我个人曾经用于.apply()
实现请求队列 - 我将一个参数数组推入队列,当需要执行它时,我获取一个元素,并将其作为处理函数的参数传递使用.apply()
,从而使如果必须将参数数组作为第一个参数传递,则代码更清洁。那是另一个例子。
一般来说,只要记住这些调用函数的方法是存在的,你可能有一天会发现它们可以方便地用于实现你的程序。
如果您有Object Oriented Programming
then call 和 apply 的经验,如果您将它与继承进行比较并从子类覆盖父类的属性或方法/函数,那么调用和应用将是有意义的。这与 javascript 中的调用类似,如下所示:
function foo () {
this.helloworld = "hello from foo"
}
foo.prototype.print = function () {
console.log(this.helloworld)
}
foo.prototype.main = function () {
this.print()
}
function bar() {
this.helloworld = 'hello from bar'
}
// declaring print function to override the previous print
bar.prototype.print = function () {
console.log(this.helloworld)
}
var iamfoo = new foo()
iamfoo.main() // prints: hello from foo
iamfoo.main.call(new bar()) // override print and prints: hello from bar