Adding Prototype to JavaScript Object Literal

Viewed 31712
STORE = {
   item : function() {
  }
};
STORE.item.prototype.add = function() { alert('test 123'); };
STORE.item.add();

I have been trying to figure out what's wrong with this quite a while. Why doesn't this work? However, it works when I use the follow:

STORE.item.prototype.add();
5 Answers

As of this writing this is possible by using the __proto__ property. Just in case anyone here is checking at present and probably in the future.

const dog = {
    name: 'canine',
    bark: function() {
        console.log('woof woof!')
    }
}

const pug = {}
pug.__proto__ = dog;

pug.bark();

However, the recommended way of adding prototype in this case is using the Object.create. So the above code will be translated to:

const pug = Object.create(dog)

pug.bark();

Or you can also use Object.setPrototypeOf as mentioned in one of the answers.

Hope that helps.

STORE = {
   item : function() {
  }
};

this command would create a STORE object. you could check by typeof STORE;. It should return 'object'. And if you type STORE.item; it returns 'function ..'.

Since it is an ordinary object, thus if you want to change item function, you could just access its properties/method with this command.

STORE.item = function() { alert('test 123'); };

Try STORE.item; it's still should return 'function ..'.

Try STORE.item(); then alert will be shown.

Related