Overriding toString prototype inside object declaration
There was already a question about overriding here toString
, and the answer is this:
function Foo() {}
Foo.prototype.toString = function()
{
return "this is Foo";
}
However my question is:
Is there a way for this prototype to override INSIDE of the object declaration like so:
function Foo() {
Foo.prototype.toString = function(){
return "this is Foo";
}
}
Or like this:
var Foo = {
Foo.prototype.toString = function(){
return "this is Foo";
}
}
It's really weird / annoying to put the prototype outside of the object declaration, but maybe it's a JavaScript quirk. I've been interested in this for a while.
source to share
As Ted Hopp mentions, there is no other way to do this yet. In ECMAScript 6, you will be able to use syntax class
that is just syntactic sugar for constuctor functions and prototypes:
class Foo {
toString() { ... }
}
For object literals it will also be shortened:
var foo = {
__proto__: {
toString() {...}
}
};
A special declaration __proto__
allows you to define a prototype within an object literal. However, since protoype is really useful when it is shared by multiple onjects, directly assigning an object to an object will be easier in this case, and also works today:
var foo = {
toString: function() {},
};
source to share
There is no good way to do what you want. The object Function
Foo
(which is usually the constructor of the object) doesn't exist until the declaration is evaluated, so there is no prototype for assigning the property toString
. Also, the assignment toString
will not be evaluated until the constructor has been executed at least once.
You don't want to initialize the toString
prototype property inside the constructor anyway , because it will assign a new function for every instance it creates Foo
. You can check if the prototype already has a property of its own toString
, but that makes the cure worse than the disease. Just stick to the recipe.
source to share
There is no way to do this, because at the time you are referencing Foo
inside the object Foo
is not yet declared. You can try doing this instead.
var Foo = {}; //assign Foo to an empty object.
and then add different properties / methods in Foo
with Object.defineProperties
and Object.assign
depending on what you want.
source to share