dynamic添加函数到function.prototype

我是nodejs的新手。 我正在写一个帮助函数来构build使用模式的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' ]; 

dynamic添加方法

 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 

我甚至试图设置这样的function

  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] 

我怎样才能dynamic地将方法设置为一个function.prototype? 非常感谢你的帮助

您正面临着这个问题,主要是因为“值”键function分配

您可以在那里find一些正在创build闭包的更改,还更改了在对象的键上分配函数语法

创build闭包以保持特定迭代的i值。

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