我想做这样的事情:
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
Run Code Online (Sandbox Code Playgroud)
当然,这是行不通的,因为 oy 在返回时会被求值。我正在寻找一种方法来返回充当吸气剂的变量。下面的例子给了我希望,这样的事情是可能的:
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
Run Code Online (Sandbox Code Playgroud)
有没有人尝试过做这样的事情?
是的,我熟悉使用不同语法对类似行为进行建模的其他方法。我只是希望这个特定的语法适用于特殊的场景。
谢谢,
克里斯
javascript ×1