【发布时间】:2017-02-15 08:36:49
【问题描述】:
这是我的用例
getSomeFields(persons, fields){
let personsWithSpecificFields = [];
_.each(persons, (person) => {
let personSpecificFields = {};
_.each(fields, (field) => {
// here im thinking to modify the field to match the method name
// ( if something like __call as in php is available)
// e.g. field is first_name and i want to change it to getFirstName
personSpecificFields[field] = person[field]();
});
personsWithSpecificFields.push(personSpecificFields);
});
return personsWithSpecificFields;
}
这是我的person class
import _ from 'lodash';
export default class Person{
// not working..
__noSuchMethod__(funcName, args){
alert(funcName);
}
constructor( data ){
this.init(data);
}
init(data) {
_.each(data, (value, key) => {
this[key] = value;
});
}
}
我已经通过Monitor All JavaScript Object Properties (magic getters and setters),尝试实现这个JavaScript getter for all properties,但没有运气。
我知道我可以通过编写另一个方法来做到这一点,它将我的first_name 转换为getFirstName 并试一试。但是有什么方法可以像在课堂上那样以ECMA-6 的方式做到这一点。
谢谢。
【问题讨论】:
-
对象实例就是任何对象。函数是对象。因此,函数也可以具有属性,也可以是其他方法。如果你想要一个“可调用对象”,就让它成为一个函数。
-
好:您搜索了其他解决方案。不好:您找到了一个并在第一个答案后停止阅读。无论如何,当您使用 ES6 时,请尝试
Proxy解决方案。 -
@Boldewyn 让我试试,先生,