gpt4 book ai didi

javascript - 是否有可能在javascript中为 "return a getter"

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

我想做这样的事情:

function x(){
var o = {};
o.__defineGetter__('y', function(){
return new Date();
});

return o.y;
}

var z = x();
console.log(z);
//Wait 1 second
console.log(z); //Date should be one second past the last printing

当然,这是行不通的,因为 o.y 是在返回时计算的。我正在寻找一种方法来返回充当 setter/getter 的变量。下面的例子让我希望这样的事情是可能的:

function x(context){
//Bind the getter to the passed in scope
context.__defineGetter__('y', function(){
return new Date();
});
}

x(this);
console.log(y);
//Wait 1 second
console.log(y); //Date is one second past last printing

有没有人试过做这样的事情?

是的,我熟悉使用不同语法为类似行为建模的其他方法。我只是希望这种特定的语法适用于特殊情况。

谢谢,

克里斯

最佳答案

答案是否定的,您不能为变量赋值,使该变量在像访问变量一样访问时表现得像一个函数。正如您在问题中指出的那样,最接近的是定义一个具有 getter 函数的属性。您不能创建按您描述的方式工作的函数的局部变量。

但是,您可以定义一个函数,该函数定义一个带有 getter 函数的全局属性(或者更确切地说,全局对象的一个​​属性),并使其看起来像您所做的那样。例如,在 ES5 中,以下内容将创建一个全局变量 y,它的作用与您描述的一样。

function x(n) { 
Object.defineProperty(this, n, {
get: function() {
return new Date();
}
});
}

x('y')

注意这只适用于非严格模式。在严格模式下,this 的值为 undefined

为什么你想要一个变量表现得像我无法理解的那样。

关于javascript - 是否有可能在javascript中为 "return a getter",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830062/

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