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

时间:2018-08-27 19:04:45

标签: javascript object ecmascript-6

我正在尝试减少我在JS对象中编写的重复代码量。我有一种方法可以使用,其中除了目标外几乎没有任何变化,我想将其提取出来,并通过对象属性名称以某种方式获取目标。希望我整理的例子有意义。

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)
      }
    }
  }
};

尝试了类似的操作,但出现错误“无法读取未定义的prop'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 个答案:

答案 0 :(得分:0)

到目前为止,我能够使其工作的唯一方法是在初始减速之外设置<nav class="navbar navbar-expand-sm navbar-light"> <a class="navbar-brand" href="#" id="brand">Stock Trader</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarColor02"> <ul class="navbar-nav"> <!--These two links should be on the left-hand side of the screen--> <router-link to="Portfolio" tag="li" active-class="active"> <a class="nav-link">Portfolio</a> </router-link> <router-link to="Portfolio" tag="li" active-class="active"> <a class="nav-link">Stocks</a> </router-link> <!--and these should be aligned to the right--> <li id="right" class="nav-item"> <a class="nav-link">End Day</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Save / Load </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Save Data</a> <a class="dropdown-item" href="#">Load Data</a> </div> </li> </ul> </div><router-link>并像@Bergi建议的那样显式声明prop1

prop2