2

This a sample of function:

function User (name) {
  this.options.name = name;
};

User.prototype.options = {
  name: 'Default'
};

var foo = new User('foo');
var bar = new User('bar');

console.log( foo.options.name );   // 'bar'
console.log( bar.options.name );   // 'bar'

The question is, how to get 'foo' and 'bar'? Thanks

Defari
  • 71
  • 6
  • There is a difference between mutating and assigning a member. When you assign a shared member on the prototype it will be shadowed, when you mutate then you change the shared member for all instances. It is explained in detail here: http://stackoverflow.com/a/16063478/1641941 – HMR Apr 24 '14 at 10:19

1 Answers1

3

When you add anything in a constructor's prototype, that will be shared by all the instances. It is the best thing for the functions, but may not be for the data. So, you want to construct the options objects in the constructor itself, like this

function User(name) {
    this.options = {
        name: name || "Default"
    };
}

When you do like this, whenever an object of User is created, each object will get its own options object. So, changing the options with one object will not affect any other object's options.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • you cant say its not best for the data.it depends on what you want, defining properties in the prototype is also useful for sharing between the instances. for example you can add an instance counter. –  Apr 24 '14 at 08:41
  • @ThorstenArtner'Austria' Altered that sentence a little. Please check :) – thefourtheye Apr 24 '14 at 08:42
  • Primitive values are usually on the prototype so they'll have a default value that can't be changed through instances because re assigning (only way to change primitives as they are immutable) will cause the member to be shadowed. – HMR Apr 24 '14 at 10:21