这里试图澄清一下。
<script>
var shoppingCart = (function () {
function calculatePriceNow() {
return this.price * this.amount;
};
return {
calculatePrice: calculatePriceNow
}
})();
var goods = {
name: 'hammer',
price: 199,
amount: 2
};
// will not work; Why? Because the function `calculatePrice` depends on their scope (`this`)
var result = shoppingCart.calculatePrice(goods);
console.log(result);
// will work; Why? We are calling the function giving it's scope explicitly using `call`
var result = shoppingCart.calculatePrice.call(goods);
console.log(result);
// will work; Why? We are calling the function giving it's scope explicitly using `apply`
var result = shoppingCart.calculatePrice.apply(goods);
console.log(result);
// How did it work with `call` and `apply`?
// They are executing `calculatePrice` in the scope of the argument `goods` which we passed to the function
// Doing so, the usage of `this` inside the function `calculatePrice` refer to the object `goods`
// Difference between `call` and `apply`?
// From MDN:
// The `apply()` method calls a function with with a given `this` value and `arguments` provided as array
// On the other hand, `call()` method calls a function with a given `this` value and `arguments` provided individually
</script>
注意事项:
不会工作;为什么?因为函数calculatePrice取决于它的作用域(this)
var result = shoppingCart.calculatePrice(goods);
console.log(result);
会工作;为什么?我们使用 call 显式调用函数并给出其范围
var result = shoppingCart.calculatePrice.call(goods);
console.log(result);
会工作;为什么?我们使用 call 显式调用函数并给出其作用域
var result = shoppingCart.calculatePrice.apply(goods);
console.log(result);
它如何与call 和apply 一起工作?
它们在我们传递给函数的参数goods 的范围内执行calculatePrice。这样做,this在函数calculatePrice内部的使用引用对象goods。
call 和 apply 之间的区别?
apply() 方法调用具有给定this 值和arguments 以数组形式提供的函数
另一方面,call() 方法调用具有给定 this 值和 arguments 单独提供的函数
致查询:
为什么第二个 sn-p 给出错误而不是答案?
如上所述,当我们这样调用时,scope 是函数的,而不是“参数”的
在第一种方法中使用'call'有什么重要性?不能
简单的函数也返回相同的答案?
简单的答案是我们给它explicit scope 使用call
call 与 apply 和 bind 相比有什么优势(如果在此使用相同)
例子?
call()、apply() 和 bind() 是 JavaScript 中所有 function 对象的一部分。如上所述,它的用法各不相同。
与call() 和apply() 相比的优势在于调用方法的灵活性(比如使用不同的参数)。