gpt4 book ai didi

javascript - 什么时候一个函数只能被调用一次?

转载 作者:行者123 更新时间:2023-12-02 16:24:35 25 4
gpt4 key购买 nike

这个问题给我带来了麻烦:

Write a function, once, (see: http://underscorejs.org/#once) that takes a function and returns a version of that function which can only be called once. [Hint: you need a closure] You probably don't want to be able to double charge someone's credit card. Here is an example of how to use it:

  var chargeCreditCard = function(num, price){
//charges credit card for a certain price
};
var processPaymentOnce = once(chargeCreditCard);


processPaymentOnce(123456789012, 200);

这是我尝试解决这个问题的方法:

var once = function(func) {
var invoked = 0;
return function() {
if (invoked === 0) {
invoked++;
return func();
}
};
};

最佳答案

我看到的唯一问题是您没有将参数传递给被调用的函数。您可以使用 arguments对象和 Function.apply()来做到这一点。

var once = function (func) {
var invoked = 0;
return function () {
if (invoked === 0) {
invoked++;
return func.apply(this, arguments);
}
};
};

演示:Fiddle

关于javascript - 什么时候一个函数只能被调用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28805010/

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