2

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;

?

Community
  • 1
  • 1
Naor
  • 23,465
  • 48
  • 152
  • 268

2 Answers2

10

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Javascript has prototype based inheritance. Which means, inheritance occurs from objects directly, unlike classical inheritance which inherits from a class.

When you do this:

Foo.protoype = Bar.prototype - you are inheriting all vars and methods from Bar object.. but any change to Foo's prototype will result in Bar's prototype to be changed(since due to above statement, Foo.prototype references Bar.prototype).

Object.create() is used to add classical inheritance like property to Foo. So instead of inheriting from the object directly, you are inheriting from Object with a specified prototype. And any change to Foo after the statement Foo.prototype = Object.create(Bar.prototype) will not change Bar.

see here for more info!

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • 2
    I wouldn't say that using `Object.create` is "classical inheritance like". It just creates an object with a specific prototype, which is the same what every constructor function does. – Felix Kling Mar 08 '13 at 22:34