假设我有一个带有以下
的javascript对象var Settings = function () {
this.timelimit = 0;
this.locked = false;
this.expires = null;
this.age = null;
};
然后我设置了一些get / set函数,如:
Settings.prototype = {
getAllAges: function () {
return self.age;
},
getTimeLimit: function () {
return self.timelimit;
},
load: function() {
data_from_local_storage = LoadLocalStorage();
}
}
在data_from_local_storage
我有与上述变量匹配的JSON变量(timelimit
,locked
等。)
问题是,对象var settings_ref = Settings()
具有所有这4个变量 - 但是在settings_ref
中分配了这3个函数 - 由于这个OO行为我需要在load()
函数内部写入:
this.timelimit = data_from_local_storage.timelimit
this.age = data_from_local_storage.age
this.locked = data_from_local_storage.locked
因为我会写的
this = data_from_local_storage
它会摧毁我的物体。
那么如何避免逐个编写所有这些变量?
.update()
函数,比如Python或其他东西.. 有人知道的快捷捷径吗?
答案 0 :(得分:2)
您可以在ES2015中使用Object.assign()
:
load: function() {
Object.assign(this, LoadLocalStorage());
}
IE中显然尚不支持它,但有一个polyfill on the MDN page:
if (typeof Object.assign != 'function') {
(function () {
Object.assign = function (target) {
'use strict';
// We must check against these specific cases.
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
(就我个人而言,我会使用Object.defineProperty()
添加方法,但这是从MDN逐字逐句的。)
(编辑虽然我猜如果你没有Object.assign()
,你可能没有Object.defineProperty()
:)
答案 1 :(得分:1)
如果将数据存储在另一个对象文本中,它会使持久化的东西变为localstorage并且更容易返回。这是一个示例..
//pretend local storage loader
function LoadLocalStorage() {
return {
timelimit: 100,
locked: true,
expires: new Date(),
age:40
}
}
var Settings = function () {
this.data = {
timelimit: 0,
locked: false,
expires: null,
age:null
}
};
Settings.prototype = {
getAllAges: function () {
return this.data.age;
},
getTimeLimit: function () {
return this.data.timelimit;
},
load: function() {
this.data = LoadLocalStorage();
}
}
var settings = new Settings;
console.log('Age before our load');
console.log(settings.getAllAges());
settings.load();
console.log('Age after our load');
console.log(settings.getAllAges());