Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript inheritance why use Object.create? [duplicate]

I saw this in StackOverflow: https://stackoverflow.com/a/7786090/289246

The answer tells to do:

DynamicBody.prototype = Object.create( PhysicsBody.prototype );

What is the reason to use Object.create?
Why can't we just use:

DynamicBody.prototype = PhysicsBody.prototype;

?

like image 641
Naor Avatar asked Aug 27 '26 11:08

Naor


1 Answers

You can (technically), but then any change you make to DynamicBody.prototype will also be made on PhysicsBody.prototype, i.e. it will affect all PhysicsBody instances, and that is usually not what you want.

Example:

function Foo() {};
Foo.prototype.say = function() {
   alert('Foo');
};
var foo = new Foo();

function Bar() {};
Bar.prototype = Foo.prototype;
Bar.prototype.say = function() {
    alert('Bar');
};

foo.say(); // alerts 'Bar'

Object.create adds one level of indirection.

like image 128
Felix Kling Avatar answered Aug 30 '26 01:08

Felix Kling