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.
You are confusing the
prototypeproperty that can be used on Constructor Functions and the internal[[Prototype]]property.All objects have this internal
[[Prototype]]property, and only thenewoperator 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.createtechnique is what you want (that method is now part of the recently approved ECMAScript 5th Edition):In the above code
confwill have its three members, but onlyaandbwill exists physically on it:Because
dexists 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).