伙计们可以解释使用Java的上下文call和apply方法吗?
为什么使用call而apply不是直接调用函数?
Answers:
您可以使用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性能。
Toy.prototype = new Product();?我对此进行了测试,删除这些行似乎对最终结果没有影响。
Toy.prototype = new Product();但留了下来Food.prototype = new Product();,所以Food继承了Product,而Toy却没有。我还在Product的原型中添加了一个方法,并从Food和Toy调用了该方法,以使继承的缺失更加明显(只需打开控制台并运行代码,Food可以调用从Product继承的方法,但是Toy不能并引发错误) 。
obj.whatever();语法,则它可能引用调用方obj 。
您可以使用.call(),当你想引起不同的执行函数this值。它this按指定设置值,按指定设置参数,然后调用函数。.call()与执行函数之间的区别是执行函数this时指针的值。当您正常执行该函数时,javascript会决定this指针是什么(通常是全局上下文,window除非将该函数作为对象上的方法调用)。使用时.call(),您可以精确指定要this设置的内容。
您可以使用.apply(),当你想传递给函数的参数是一个数组。 .apply()也会导致函数以特定this值执行。 .apply()当您不确定地来自其他来源的参数数量时,最常使用该参数。它也经常通过使用特殊的局部变量来将参数从一个函数调用传递到另一个函数,该局部变量arguments包含传递给当前函数的参数数组。
如果您有经验,Object Oriented Programming那么将继承与继承进行比较,并从子类覆盖父类的属性或方法/函数,则调用并应用将很有意义。与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
我想不出任何正常情况,将thisArg设置为不同的东西是使用apply的目的。
apply的目的是将值数组传递给希望将这些值作为参数的函数。
它已被点播运营商取代为所有常规日常使用。
例如
// Finding the largest number in an array
`Math.max.apply(null, arr)` becomes `Math.max(...arr)`
// Inserting the values of one array at the start of another
Array.prototype.unshift.apply(arr1, arr2);
// which becomes
arr1 = [...arr2, ...arr1]
thisArg致电时的重点apply(),call()这似乎是您问题的核心。您需要了解Javascript中的函数调用原语