当且仅当使用它时,如何在 JavaScript 中计算变量? [英] How do I compute a variable in JavaScript if and only if it is used?
问题描述
这就是我现在正在做的事情.
This is what I'm doing right now.
var foo = function() {
var x = someComplicatedComputationThatMayTakeMoreTime();
this.foo = function() { return x; };
return x;
}
它有效,但只有当 foo 被调用为这样的函数时
It works but only if foo is called as a function like so
foo();
但是如果我想将它称为带有值的普通变量呢?我可以将代码修改为
But what if I want to call it as a normal variable with a value? I could modify the code to be
var foo = function() {
var x = someComplicatedComputationThatMayTakeMoreTime();
this.foo = x;
return x;
}
这将允许我只将它作为函数调用一次,然后作为常规变量调用一次.但这仍然不是我想要的.此外,如果它不小心再次作为函数调用,返回错误,它会变得复杂.
That would allow me to only call it once as a function and after that as a regular variable. But it's still not what I want. Plus it gets complicated if it accidentally gets called as a function again, returning an error.
这在 JavaScript 中是否可行?
Is this even possible in JavaScript?
顺便说一句,这是针对 Chrome/Firefox 扩展程序的,因此 IE 兼容性无关紧要.
BTW, this is for a Chrome/Firefox extension, so IE compatibility does not matter.
最终使用 toString 因为 getter 不允许我重新定义整个属性,必须有一个函数与之关联.并且 toString 具有更清晰的语法.
Ended up using toString because getters don't allow me to redefine the whole attribute, a function must be associated with it. And toString has cleaner syntax.
推荐答案
如何使用 toString?
How about using toString?
var foo = function() {
function someComplicatedComputationThatMayTakeMoreTime() {
//your calculations
}
return {
toString: function() {
return someComplicatedComputationThatMayTakeMoreTime();
}
}
}
编辑.使用单例(我认为它被称为):
EDIT based on comment. Use a singleton (I think it's called):
myObject.prop = (function(){
function someComplicatedComputationThatMayTakeMoreTime() {
//your calculations
}
return {
toString: function() {
return someComplicatedComputationThatMayTakeMoreTime();
}
}
})()
这篇关于当且仅当使用它时,如何在 JavaScript 中计算变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!