javascriptprototypeobject-literal

Adding Prototype to JavaScript Object Literal


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();

Solution

  • The prototype object is meant to be used on constructor functions, basically functions that will be called using the new operator to create new object instances.

    Functions in JavaScript are first-class objects, which means you can add members to them and treat them just like ordinary objects:

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

    A typical use of the prototype object as I said before, is when you instantiate an object by calling a constructor function with the new operator, for example:

    function SomeObject() {} // a constructor function
    SomeObject.prototype.someMethod = function () {};
    
    var obj = new SomeObject();
    

    All the instances of SomeObject will inherit the members from the SomeObject.prototype, because those members will be accessed through the prototype chain.

    Every function in JavaScript has a prototype object because there is no way to know which functions are intended to be used as constructors.