JS instance properties
The problem with this.property in the constructor is we have instance properties
by justinwyllie
JavaScript
var Test = function(word) {
this.word = word;
}
var test1 = new Test('hello1');
var test2 = new Test('hello2');
console.log(test1.word);
console.log(test2.word);
test1.word = 'xxx';
console.log(test1.word);
//still hello2 - we changed the instance for test1 only
console.log(test2.word);
//
var Test2 = function(obj) {
this.obj = obj;
}
var testObj = {'a':'b'};
var test1 = new Test2(testObj);
var test2 = new Test2(testObj);
console.log(test1.obj);
console.log(test2.obj);
test1.obj.a = 'c';
console.log(test1.obj);
//oh. because it has kept its reference
//test2's property is now changed too
//maybe use object.assign to break the reference in the constructor?
console.log(test2.obj);