javascript OO如何用一些JSON变量更新self参数

javascript OO how to update self parameters with some JSON variable

本文关键字:变量 更新 self 参数 JSON OO 何用一 javascript      更新时间:2023-09-26

假设我有一个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());