这是我从属性哈希创建对象的方法:
var object = new function (data) {
var self = this;
self.property = data.property;
self.anotherProperty = data.anotherProperty;
self.method = function () { return 'something'; }
self.update = function (newData) {
//what is here ?
//i could have written:
self.property = newData.property;
self.anotherProperty = newData.anotherProperty;
//but why not reuse the constructor?
}
};
我想知道如何重用此函数(构造函数)来从哈希更新对象。 那样:
object.update(newData)
将从newData
哈希更新当前对象属性,与构造函数中的方式相同。
答案 0 :(得分:3)
给构造函数一个名字?
function MyNotReallyClass(data){
var self = this;
self.property = data.property;
self.method = function () { return 'something'; }
self.update = MyMyNotReallyClass;
};
你现在可以打电话了
var obj = new MyNotReallyClass(data);
var obj2 = new MyNotReallyClass(data);
和
obj.update(data);
我希望这会有所帮助..我不是百分百肯定,因为我也在学习......但是试试吧;)
编辑:在看完你的这条评论后:“但那会返回一个新的实例,不是吗?我不想要。”
我认为您可以编写Update函数并在构造函数中调用它
var object = new function (data) {
var self = this;
self.update = function (newData) {
self.property = data.property;
self.method = function () { return 'something'; }
// and other things You want to do in constructor and update
}
self.update(data);
}