0

I use the code below in Firefox to set the prototype inheritance relationship between two objects:

var a = {};
var b = {};

b.__proto__ = a;
a.dosomething = function() {
   alert('ok');
};
b.dosomething();  //ok

but it only works on Firefox due to __proto__ being only available in Firefox.

In other web browsers, if a and b were created using some constructor function, I could use

b.constructor.prototype = a;

to set the inheritance relationship.

But in the case above, the constructors of a and b are both Object. I can not change the prototype of Object.

Is there any way to set the inheritance relationship except by using __proto__?

Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
arachide
  • 8,006
  • 18
  • 71
  • 134
  • Did you mean `__proto__`? – Oriol Oct 10 '16 at 22:00
  • yes, it is __proto__ – arachide Oct 10 '16 at 22:01
  • In the above code aren't you setting b as a prototype of a? In the below code why are you doing `b.constructor.prototype = a` instead of `b.prototype=a`? Also you are right object is the mother prototype in js, i ask just to understand the issue better. – Ali Somay Oct 10 '16 at 22:06

2 Answers2

2

You can use Object.create. It creates an object whose prototype is the object passed to it.

var a = {};
var b = Object.create(a);

a.dosomething = function() {
   alert ('ok');
};
b.dosomething(); // ok

You can also use Object.setPrototypeOf for objects that already exist. You really, really should not do this if you can avoid it. It leads to serious performance issues.

var a = {};
var b = {};

Object.setPrototypeOf(b, a);

a.dosomething = function() {
   alert ('ok');
};
b.dosomething(); // ok
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
2

Do not alter the prototype of an existing object.

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().

And if you do so, the standard way is Object.setPrototypeOf, not __proto__.

The proper way is

var a = {};
var b = Object.create(a);
a.dosomething = function(){
  console.log('ok');
};
b.dosomething();

Your b.constructor.prototype = a; approach is useless. If b is an instance of a constructor C, that code will only affect instances constructed after the change, but not b.

Oriol
  • 274,082
  • 63
  • 437
  • 513