John John - 6 months ago 3x
Javascript Question

Adding Prototype to JavaScript Object Literal

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

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:



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'); };

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.