动态添加函数到function.prototype

时间:2017-03-24 22:38:13

标签: javascript node.js

我是nodejs的新手。 我正在编写一个帮助函数来使用模式构建JSON,我正在尝试添加函数(主要是setter)来设置值。以下是它的简单版本。

function Task() {
  this.action = {};
  this.schedule = {};
}

function capitalize(str) {
  return `${str[0].toUpperCase()}${str.slice(1)}`;
}

const scheduleProps = [
'startAt',
'repeatEvery',
'endAt',
'count',
'interval'
];

动态添加方法

for(var i=0; i<scheduleProps.length; i++) {
  Object.defineProperty(Task.prototype, `set${capitalize(scheduleProps[i])}`, {
    enumerable: true,
    configurable: false,
    writable: true,
    value: (value) => {
      this.schedule[scheduleProps[i]] = value;
    }
  });
}

当我按以下方式调用时,我希望obj.schedule.repeatEvery包含值10。

obj = new Task();
obj.setRepeatEvery(10);

相反,我得到

TypeError: Cannot set property 'repeatEvery' of undefined

我甚至尝试设置这样的功能

  Task.prototype[`set${capitalize(scheduleProps[i])}`] = (val) => {
    this.schedule[scheduleProps[i]] = val;
  }

在这种情况下,我得到

TypeError: Cannot set property 'interval' of undefined
at Task.(anonymous function) [as setRepeatEvery]

如何动态地将方法设置为function.prototype? 非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您正面临问题,主要是因为功能分配&#34;值&#34;键

你可以找到一些更改,即创建一个闭包,并且还更改了在对象键处分配函数语法。

创建

关闭以维持该特定迭代的i值。

&#13;
&#13;
function Task() {
  this.action = {};
  this.schedule = {};
}

function capitalize(str) {
  return `${str[0].toUpperCase()}${str.slice(1)}`;
}

const scheduleProps = [
    'startAt',
    'repeatEvery',
    'endAt',
    'count',
    'interval'
];

for(var i=0; i<scheduleProps.length; i++) {
  Object.defineProperty(Task.prototype, `set${capitalize(scheduleProps[i])}`, {
    enumerable: true,
    configurable: false,
    writable: true,
    value: (function(i) { return function(value) { this.schedule[scheduleProps[i]] = value;} })(i)
  });
}

obj = new Task();
obj.setRepeatEvery(10);
&#13;
&#13;
&#13;