I have a class definition that is part of a class definition.
var someObject = {
someClass: function() {
this.someMethod = function() {
alert('hello');
};
}
}
I have been told that I should use prototype to add methods, as it then only needs to be created once for all instances of the object. The problem is that it seems I need to add the prototyped method after the constructor function is defined, like this…
var someObject = {
someClass: function() {
}
}
someObject.someClass.prototype.someMethod = function() {
alert('hello');
};
Ideally however I would like to define the prototyped methods within the constructor function like this…
var someObject = {
someClass: function() {
this.prototype.someMethod = function() {
alert('hello');
};
}
}
This causes an error however stating that prototype is null or not an object. Is there a way to accomplish what I would like, or is this not possible?
You can make it work by using
arguments.calleeor – if you don’t overwrite the.prototypeproperty of your constructor function –this.constructorinstead of plainthis, ieHowever, putting the function expression back into the constructor defeats the whole purpose of the exercise – it doesn’t matter that you store the reference to the function object in the prototype instead of the instance, you’re still creating a new one on each constructor invocation!
One possible solution is using an anonymous constructor instead of an object literal, which gets you an additional scope for free:
See Paul’s answer for an equivalent solution using object literals and a wrapper function, which might be more familiar.