Setting prototype for Object Literal
javascript, prototypal-inheritance, prototype
Solution
Objects inherit from their constructor's prototype property, not their own. The constructor's prototype is assigned to the internal `[[Prototype]]` property that is available in some browsers as the `__proto__` property.
So for `b` to inherit from `a`, you need to put `a` on `b`'s inheritance chain, e.g.
Classic prototype inheritance:
var a = {a: 'a'};
function B(){}
B.prototype = a;
var b = new B();
alert(b.a); // a
Using ES5 Object.create:
var a = {a: 'a'};
var b = Object.create(a);
alert(b.a); // a
Using Mozilla `__proto__`:
var a = {a: 'a'};
var b = {};
b.__proto__ = a;
alert(b.a); // a
Problem
Let's say I have the following code; ``` var A = {a:10}; var B = {b:20}; B.prototype = A; alert(B.a); ``` I am getting undefined for B.a . Am I doing something wrong? How do I set the prototype for object literal ? I know how to do for Constructor object. So the following code works perfect ``` function A(){this.a=10} function B(){this.b=20} B.prototype = new A(); b = new B; alert(b.a); ``` How do I do it for object literal ?
Related problems
- How does JavaScript .prototype work?
- How does __proto__ differ from constructor.prototype?
- How to set the prototype of a JavaScript object that has already been instantiated?
- __proto__ VS. prototype in JavaScript
- [[Prototype]] vs prototype: ..what is the difference? (MyCons.__proto__ === MyCons.prototype) equals FALSE