Setting prototype for Object Literal-Collection of common programming errors

The prototype property is usually present in a Function object. This prototype should be an object, and this object is used to define the properties of an object created with a constructor.

// Plain object, no prototype property here.
var plainObject = {one: 1, two: 2};

// Constructor, a prototype property will be created by default
var someConstruct = function() {

  // Constructor property
  someConstruct.constructProp = "Some value";

  // Constructor's prototype method
  someConstruct.prototype.hello = function() {
    return "Hello world!";
  }
};

// Another constructor's prototype method
someConstruct.prototype.usefulMethod = function() {
  return "Useful string";
}

var someInstance = new someConstruct();
console.log(someInstance.hello()); // => Hello world!
console.log(someInstance.usefulMethod()); // => Useful string

console.log(someConstruct.constructProp); // => Some value
console.log(someConstruct.prototype); // => {usefulMethod: function, hello: function}

console.log(plainObject.prototype); // => undefined

So, plain objects have no prototypes. Functions which work as constructors do have prototypes. These prototypes are used to fill an instance created with each construct.

Hope that helps 🙂

Originally posted 2013-11-10 00:17:00.