JavaScript prototype limited to functions?

function, javascript, object, prototype

Solution

You are confusing the `prototype` property that can be used on Constructor Functions and the internal `[[Prototype]]` property.

All objects have this internal `[[Prototype]]` property, and only the `new` operator when you call it with a constructor function is allowed to set it (through the `[[Construct]]` internal operation).

If you want to have prototypal inheritance with object instances (without using constructors), the Crockford's `Object.create` technique is what you want (that method is now part of the recently approved ECMAScript 5th Edition):

// Check if native implementation available
if (typeof Object.create !== 'function') {
  Object.create = function (o) {
    function F() {}  // empty constructor
    F.prototype = o; // set base object as prototype
    return new F();  // return empty object with right [[Prototype]]
  };
}

var confProto = {
  d: 16
};
var conf = Object.create(confProto);
conf.a = 2;
conf.b = 4;

In the above code `conf` will have its three members, but only `a` and `b` will exists physically on it:

conf.hasOwnProperty('a'); // true 
conf.hasOwnProperty('b'); // true
conf.hasOwnProperty('d'); // false

Because `d` exists on the conf `[[Prototype]]` (`confProto`).

The property accessors, `.` and `[]` are responsible to resolve the properties looking up if necessary in the prototype chain (through the `[[Get]]` internal method).

Problem

o.prototype = {...} is working only if o is a Function. Suppose I've the following Code ``` conf = { a: 2, b: 4 }; conf.prototype = { d: 16 } ``` conf.a and conf.b is OK and returns proper values. But conf.d doesn't return 16 rather it goes undefined. Is there any solution suck that prototype based generalization can also be applied on these type of Objects.

Original source