0

If prototype are shared by all instances, why it doesn't work?

var Module = function(){};

Module.prototype.sharedValue = "value";

var a = new Module();
var b = new Module();

a.sharedValue = "other value";

console.log(b.sharedValue) // it prints 'value' and not 'other value'
MuriloKunze
  • 15,195
  • 17
  • 54
  • 82
  • 1
    Because you're modifying the `sharedValue` of `a` only. – BenM Mar 14 '14 at 20:10
  • possible duplicate of [Static variables in JavaScript](http://stackoverflow.com/questions/1535631/static-variables-in-javascript) – Sanoob Mar 14 '14 at 20:11

2 Answers2

2

a.sharedValue = 'other value' assigns the 'other value' value to the sharedValue property of the a instance only.

The way the prototype chain works, is that property access will look at the object instance for whether it contains a specific property, and if it doesn't find the property, it will traverse up the prototype chain until it either:

  1. finds the property and returns the value of that property at whatever level of the prototype
  2. doesn't find the property on any of the prototypes and returns undefined

You should also note that modifying a.sharedValue = 'other value' will not have any affect on Module.prototype.sharedValue.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
2

To assign to the prototype, you need to do it explicitly:

Module.prototype.sharedValue = "other value";

Otherwise it assigns the property to the instance, which masks the value on the prototype.

greim
  • 9,149
  • 6
  • 34
  • 35