1

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 ?

1
  • It's just a function, lifer any other. You could cache the value, for example by executing a function that returns a function. Commented May 16, 2012 at 0:13

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

I think you are looking for something like memoization.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.