0

Given the following code:

var Car = function() {};

Car.prototype = {
  wheels: {
    rims: 'steel'
  }
}

var volvo = new Car;
var mercedes = new Car;

volvo.wheels.rims = 'aluminium';

console.log(volvo.wheels.rims, mercedes.wheels.rims); // 'aluminium', 'aluminium'

Can you explain why instance mercedes of Auto automatically inherits the sub-property definition for rims from volvo?

Note the following code works as expected with same setup:

volvo.wheels = 4;

console.log(volvo.wheels, mercedes.wheels); // 4, Object { rims: 'steel' }
Simon
  • 7,182
  • 2
  • 26
  • 42
  • 3
    Because `wheels` is a prototype property. – dfsq Oct 08 '14 at 15:52
  • 4
    Every instance of `car` shares *the same* object `wheels`. Instance specific properties should be created inside the constructor. – Felix Kling Oct 08 '14 at 15:52
  • Maybe the following can help in understanding prototype, constructor and mutating versus assigning members (in combination with prototype). http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Oct 09 '14 at 02:45

1 Answers1

2

You only ever create a single object for wheels.

You assign this object to the prototype, so every instance inherits its value.

Javascript will never automatically copy an object.

Instead, you should create the object in the constructor so that you get a new object for each instance.

Simon
  • 7,182
  • 2
  • 26
  • 42
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964