Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting prototype for Object Literal

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 ?

like image 563
copenndthagen Avatar asked Dec 06 '22 08:12

copenndthagen


1 Answers

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
like image 82
RobG Avatar answered Dec 27 '22 05:12

RobG