試圖用頭戴圍繞javascript組合使用assign。我的基礎對象上的屬性意外地在實例之間共享。我究竟做錯了什麼?我有...Javascript Object Object with assign&Object.create
Stat.js:
import assign from 'object-assign';
var Stat = assign({}, {
_value: undefined,
get: function() {
return this._value;
},
set: function(n) {
var max = this.getMax();
if(n > max) {
this._value = max;
} else {
this._value = n;
}
},
getMax: function() {
return 1;
}
});
module.exports = Stat;
HitPoints.js:
import assign from 'object-assign'
import Stat from './Stat.js';
var HitPoints = assign({}, Stat, {
getMax: function() {
return 100;
}
});
module.exports = HitPoints;
Unit.js:
import assign from 'object-assign';
import HitPoints from 'HitPoints.js';
var Unit = assign({}, {
hp: Object.create(HitPoints)
}
);
module.exports = Unit;
用法:
import Unit from 'Unit.js';
var u1 = Object.create(Unit);
console.log(u1.hp.get()); // undefined - ok
u1.hp.set(11);
console.log(u1.hp.get()); // 11 - ok
var u2 = Object.create(Unit);
console.log(u2.hp.get()); // 11 - ???
u2.hp.set(22);
console.log(u1.hp.get()); // 22 - ???
console.log(u2.hp.get()); // 22
感謝您的幫助......
這裏使用'assign'沒有任何好處。 'hp'是共享的,因爲'u1'和'u2'都有'Unit'(單個對象)作爲原型。 'Object.create(Unit)'不會創建'Unit'的*副本,如果這就是你的想法。 –
@Felix Kling我明白了...所以,我該如何做到這一點。我是來自AS3的javascript n00b。以上內容受到JavaScript對象[這個解釋](http://www.datchley.name/delegate-object-to-classical-inheritance/)的啓發。 –
我建議使用構造函數:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Custom_objects。 –