0

How do getter or setter works on object in javascript ?

i.e.

In python if I call a nonexistent method on an object I could intercept the call via getter and setter and in turn return from getter and setter.

How do I do similar functionality in JavaScript ?

https://github.com/Flotype/now/blob/master/lib/client/now.js implements this functionality somehow. I didn't understand the trick. can anyone explain ?

4
  • __defineGetter__ Commented Aug 30, 2012 at 14:22
  • 1
    @arxanas careful that's deprecated and only works in mozilla afaik Commented Aug 30, 2012 at 14:27
  • its non standard and deprecated, what about other methods ? ( or may be its not possible ? ) Commented Aug 30, 2012 at 14:27
  • I don't think there are other methods currently, the main workaround is to access everything by a main get and set method which then does the checking inside that method. Commented Aug 30, 2012 at 14:29

2 Answers 2

1

Creating the same functionality is virtually impossible in Javascript. My best guess would be something like this:

var getter = function (propName) { 
    if (propName in this) { 
        return this[propName]; 
    } else { 
        return "no prop"; 
    } 
};

You can call this function on any object you like using this syntax:

a = { "test": "yes" };
b = {}
console.log(getter.call(a, "test"));
console.log(getter.call(b, "test"));

It's not the best solution but I don't think there's a better way.

Sign up to request clarification or add additional context in comments.

Comments

1

1) You can use non-standart mozilla __noSuchMethod__ property.

2) EcmaScript 6 Harmony propose the Proxy object. See Simulating __noSuchMethod__

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.