Javascript getter如何工作?

时间:2012-05-15 23:44:29

标签: javascript oop

我在我的应用程序中长时间使用javascript getter,并且总是想到

他们的工作方式如下:

myobject.prototype.__defineGetter__('something', function () {
   return DoSomeHeavyComputation() // this will be executed only once and will be saved
})

new myobject()
myobject.something // the computation will be done here
myobject.something // no computation will be done here.

我刚刚发现计算每次都完成......

是否有资源或其他东西显示它们实际上如何运作?

3 个答案:

答案 0 :(得分:1)

这篇文章非常棒,真正深入了解了原型设计和对象实例化的细节:http://dmitrysoshnikov.com/ecmascript/chapter-7-2-oop-ecmascript-implementation/

答案 1 :(得分:1)

如果在对象的属性上定义getter,则每次尝试访问该属性时都会调用它。

obj.prop;

如果要缓存结果,则应手动执行。

如果在对象的属性上定义一个setter,则每次设置属性时都会调用它。

obj.prop = 1;

答案 2 :(得分:0)

我认为你正在寻找像记忆这样的东西。

http://documentcloud.github.com/underscore/#memoize