gpt4 book ai didi

javascript - 在 JavaScript 中使用 call 与通过简单函数返回

转载 作者:行者123 更新时间:2023-11-28 18:22:34 25 4
gpt4 key购买 nike

以下是根据对象数据计算总量的两种方法:

代码片段 1

var shoppingCart = (function(){
function calculatePriceNow() {
return this.price * this.amount;
};
return {
calculatePrice : calculatePriceNow
}
})();

var goods = {
name : 'hammer',
price: 199,
amount : 2
};

var result = shoppingCart.calculatePrice.call(goods);
console.log(result);

代码片段 2

var shoppingCart = (function(){
function calculatePriceNow(obj) {
return obj.price * obj.amount;
};
})();

var goods = {
name : 'hammer',
price: 199,
amount : 2
};

var result = shoppingCart.calculatePriceNow(goods);
console.log(result);

结果 1:

398

结果 2:

enter image description here

我的查询

  1. 为什么第二个片段给出错误而不是答案?
  2. 在第一种方法中使用“call”的重要性是什么?简单的函数不能也返回相同的答案吗?
  3. 如果在此示例中使用相同的方法,那么相对于 applybind 调用有何优势?

最佳答案

我会尽力解决您的每个问题。

Why second snippet gives error instead of answer?

因为,您正在使用 IIFE,但您没有返回任何内容。如果您没有在 javascript 中(在函数中)显式返回某些内容,则意味着返回 undefined。因此,您的错误“不能...未定义”。所以你想返回它内部的那个函数。

What is the importance of using 'call' in the first method? Cannot simple function also return the same answer?

call(和apply)的重要之处在于“绑定(bind)”上下文的能力。那么,在您的代码片段 1 中,您是否看到对 this 的引用。好吧,当您使用 call 调用该函数时 - 您正在将 goods 的上下文“绑定(bind)”到 this。因此,当您说 this.price 时,您就是在说 goods.price。因为 call 使您能够做到这一点。

What is advantage of call over apply and bind if same used in this example?

其他人可能知道其中的复杂性,但我相信 call 在这种情况下很好。如果,除了设置“上下文”之外,您还传递了一些参数 - 例如数组,那么您将使用 applybind 的使用返回一个新函数,因此存在内存消耗。它就像部分应用程序 - 你给出一个参数,上下文 - 它返回一个新函数 - 等待。我想说,按照你的用法,通话是完美的。我想听听其他人的想法。

关于javascript - 在 JavaScript 中使用 call 与通过简单函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39697000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com