質問

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

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top