3

Given the following piece of code:

function Constructor(){}

var proto = Constructor.prototype;

proto.someMethod = function(){};
proto.someProperty = "some value";

proto.obj = {};

Object.defineProperty(proto.obj, "prop", {
    get: function() {
            return this.someMethod() + this.someValue;   
        }
});

var instance = new Constructor();
instance.obj.prop; // => Uncaught TypeError: undefined is not a function

A function used as getter or setter has its 'this' value bound to the object from which the property is being set or gotten. The 'this' value of the getter function in the code points to 'proto.obj'. Is there a way of binding the getter function's 'this' value to instances of 'Constructor' in order to be able to access properties and methods?

  • Not to the "current" instance if you want to define `obj` on the prototype, no. – Bergi Feb 25 '15 at 12:58
  • It is indeed a duplicate. Even though I searched for a suitable question that addressed this issue, StackOverflow's suggestions didn't seem to be appropriate. I will delete this question as I am against clutter! Thanks for your help. – Luis Caceres Feb 25 '15 at 13:05
  • No, don't delete the question, it will be found by others who search and serve as a signpost for them. Admittedly, those questions are hard to find, it's only that I have them on my personal dupe list :-) – Bergi Feb 25 '15 at 13:09

0 Answers0