Amir Abu Shareb
Amir Abu Shareb

Reputation: 164

How do Javascript getters work?

i'v been using javascript getters for a long time in my applications, and always thought

that they work like this:

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.

i just found out the computation is done each time...

is there a resource or something that shows how do they actually work ?

Upvotes: 1

Views: 1243

Answers (3)

timrwood
timrwood

Reputation: 10671

I think you are looking for something like memoization.

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

Upvotes: 0

Amjad Masad
Amjad Masad

Reputation: 4035

If you define a getter on a property of an object it will be called each time you try to access that property.

obj.prop;

If you want to cache the result you should do it manually.

Similary if you define a setter on a property of an object it will be called each time you set the property.

obj.prop = 1;

Upvotes: 1

brandwaffle
brandwaffle

Reputation: 1262

This article is awesome and gets really into the nitty-gritty of prototyping and object instantiation: http://dmitrysoshnikov.com/ecmascript/chapter-7-2-oop-ecmascript-implementation/

Upvotes: 0

Related Questions