Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 907
John Avatar asked Oct 20 '09 04:10

John


People also ask

Do object literals have prototype?

The object literals are using undefined and number 15 to setup __proto__ value. Because only an object or null are allowed to be prototypes, objUndefined and objNumber still have their default prototypes: plain JavaScript objects {} .

How do you set a prototype of an object?

The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. All JavaScript objects inherit properties and methods from a prototype. It is generally considered the proper way to set the prototype of an object.

How do you add a prototype to a function?

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


1 Answers

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.

like image 76
Christian C. Salvadó Avatar answered Sep 24 '22 01:09

Christian C. Salvadó