javascript OO如何用一些JSON变量更新self参数
javascript OO how to update self parameters with some JSON variable
假设我有一个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
它将破坏我的对象。
那么我怎样才能避免一个一个地写这些变量呢?
- 函数内的for循环
- 在这个例子中只有4个但是还有更多我不能每次都写
- 我正在寻找一些
.update()
函数,如Python或其他…
有没有人知道的快捷方式?
你可以在ES2015中使用Object.assign()
:
load: function() {
Object.assign(this, LoadLocalStorage());
}
显然在IE中还不支持,但是在MDN页面上有一个polyfill:
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的逐字记录。)
(edit虽然我猜如果你没有Object.assign()
你可能也没有Object.defineProperty()
:)
如果您将数据存储在另一个对象文本中,那么将内容持久化到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());
相关文章:
- React:使用索引变量更新嵌套集合
- 范围变量更新,但不更新视图
- 正在将代码库中的C#变量更新到asp.net
- 使用变量更新剑道图表系列的数据会导致重绘将列从图表上绘制出来
- MongoDB 用变量更新数组
- 将变量更新为函数中的参数
- Javascript-变量更新
- 使用Javascript和PHP变量更新页面上的数据
- Angular js 在
标签上的变量更新$scope动画
- 如何通过参数变量更新对象的属性值
- 如何在范围变量更新时更新模板
- 简单的变量更新和写入页
- 函数在变量更新后的某个时间点执行
- javascript OO如何用一些JSON变量更新self参数
- 使用$set中的变量更新mongodb的node.js
- 将声明的null变量更新为布尔值
- 在查询部分使用变量更新查询
- 如何在回调中使用变量更新文档?
- 通过AJAX用PHP变量更新URL
- 防止在没有javascript的情况下在页面刷新后进行变量更新