Pregunta

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

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top