Properties don't have to be on prototypes, you can just add them directly to instances:
var f = new Foo();
f.myProp = { bar: 3 };
I know that. Its not what I want.
The only way I can think of to do this via the prototype with a property (not a method; @meager has a solution using a method) is an ugly hack where you define the property on the prototype with Object.defineProperty
(ES5-only) and then redefine it on first access, like this:
Object.defineProperty(Foo.prototype, "myProp", {
get: function() {
var obj = { bar: 3 };
Object.defineProperty(this, "myProp", {
get: function() {
return obj;
},
set: function(value) {
obj = value;
}
});
return obj;
}
});
I would not recommend that. :-)
An alternative would be to throw a facade in front of Foo
, like this:
var OriginalFoo = Foo;
Foo = function() {
OriginalFoo.apply(this, arguments);
this.myProp = { bar: 3 };
};
Foo.prototype = Object.create(OriginalFoo.prototype);
That would, of course, only apply to objects created via new Foo
after this code executed.