views:

460

answers:

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

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();
+10  A: 

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.

CMS
John
You're welcome @John, glad to help!
CMS
Great explaination! thumbs up!!
Ramiz Uddin
A: 

You can use JSON revivers to turn your JSON into class objects at parse time. The EcmaScript 5 draft has adopted the JSON2 reviver scheme described at http://JSON.org/js.html

var myObject = JSON.parse(myJSONtext, reviver);

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

myData = JSON.parse(text, function (key, value) {
    var type;
    if (value && typeof value === 'object') {
        type = value.type;
        if (typeof type === 'string' && typeof window[type] === 'function') {
            return new (window[type])(value);
        }
    }
    return value;
});
Mike Samuel
this is not about JASON. John is very clearn about what he is asking and CMS explained it very well.
Ramiz Uddin