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.

+3


source to share


5 answers


I think what you are looking for is below.

function Foo() {
    this.toString = function() {
        return "this is Foo";
    }
}

      



Note. The disadvantage of this method is that the method is toString()

recreated every time you create a new instance Foo

.

+3


source


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() {},
};

      

+8


source


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.

+3


source


function Foo() {
    return {
        toString: function () {
            return "this is foo";
        }
    };
}

var foo = new Foo();
console.log(foo.toString());

      

+1


source


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.

+1


source







All Articles