gpt4 book ai didi

javascript - 确保函数在对象字面量中只被调用一次的方法

转载 作者:行者123 更新时间:2023-11-30 16:54:09 24 4
gpt4 key购买 nike

SO 上有很多方法可确保函数仅被调用一次,但我发现没有一个方法可以解决以下上下文和目标。上下文是对象字面量中的一个函数,目标是将此实用程序放在 Function.prototype 上,或者以某种方式使其不那么冗长。目前我正在这样做:

var HugeLiteral={
subComponent:{
_name:'subComponent'
,_privateFnsEtc:function(){
}
,_init:function(){
// start of thing I would like to "Macro-ize"
if (arguments.callee.initialized) {console.error('already initialized');return;}
arguments.callee.initialized=true;
// End
//
// I would like to say something like
if (!arguments.callee._proceed()) {return;}// _proceed logs the error
//
// or alternatively
globalRunOnceCheckFn();// uses stack to get this function and do a throw
// or
maybeWrapCallingFunction(this);
//
codeToExecuteOnceHere();
//
// or this method which would tend to lock me into a single return point
this._init=this._init.guardFnOnFunctionPrototype;
}
}
,_init:function(){
// Here I could walk HugeLiteral and do whatever,
// but I am not sure I like wrapping the _inits.
}
};

我的主要要求是执行此操作的方式必须在函数内部运行,我知道我可以在外部包装函数以使其运行一次。

最佳答案

var obj = {
foo: function() {
this.foo = function(){};
return 'once';
}
};

console.log(obj.foo()); // 'once'
console.log(obj.foo()); // undefined

关于javascript - 确保函数在对象字面量中只被调用一次的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30008477/

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