代码之家  ›  专栏  ›  技术社区  ›  Batman

我可以用一个对象作为其他对象的模板吗?

  •  0
  • Batman  · 技术社区  · 6 年前

    myObject = {
      d: {
        get: function(list, id) {
          // do stuff
        },
        prop1: {
          data: [],
          list: myObject.config.lists.prop1.guid,
          get: function(a,b) {
            myObject.d.get(a,b)
          }
        },
    
        // I want to write this once and use the object key ("prop2") as an argument
        prop2: {
          data: [],
          list: myObject.config.lists.prop2.guid,
          get: function(a,b) {
            myObject.d.get(a,b)
          }
        }
      }
    };
    

    尝试了类似的操作,但出现错误“无法读取未定义的属性'spec'”

    myObject = {
      d: {
        get: function(list, id) {
          // do stuff
        }
      },
    
      // Use this to duplicate shared funtions for similar
      spec: function(target) {
        return {
          data: [],
          list: myObject.config.lists[target].guid,
    
          get: function() {
            myObject.d.get(a, b);
          },
          update: "",
          delete: ""
        };
      },
    
      // some how return `myObject.spec.get()`, allowing me to use myObject.d.prop1.get()
      prop1: myObject.spec.apply(this, "prop1"),
      prop2: myObject.spec.apply(this, "prop2")
    };
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Batman    6 年前

    到目前为止,我唯一能让它工作的方法就是 prop1 prop2 target 就像@Bergi建议的那样:

    var myObject = myObject || {};
    myObject = {
      d: {
        get: function(list, id) {
          // do stuff
        }
      },
    
      // Use this to duplicate shared funtions for similar
      spec: function(target) {
        return {
          data: [],
          list: target,
    
          get: function() {
            myObject.d.get(a, b);
          },
          update: "",
          delete: ""
        };
      }
    
    };
    
    // some how return `myObject.spec.get()`, allowing me to use myObject.d.prop1.get()
    myObject.prop1 = myObject.spec("prop1");
    myObject.prop2 = myObject.spec("prop2");