문제

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