所以我已经在我的主要javascript初始化文件中使用了一大堆这样的东西,我需要大约20-30个这样的东西。有没有一种方法可以从不同的文件中导出这些文件,这样我就可以清除我的主文件?
Reflect.defineProperty(numerator, 'getBalance', {
value: function getBalance(id) {
const TEMPLATEUser = numerator.get(id);
return TEMPLATEUser ? TEMPLATEUser.balance : 0;
},
});发布于 2020-07-02 21:25:10
我认为你可以创建一个函数来抽象你正在做的事情。假设您在一个名为file1.js的文件中定义了此函数,并且希望在file2.js中使用它。
// file1.js
module.exports.defineGetBalance = obj => {
Reflect.defineProperty(obj, 'getBalance', {
value: function getBalance(id) {
const TEMPLATEUser = obj.get(id);
return TEMPLATEUser ? TEMPLATEUser.balance : 0;
},
});
};现在,您可以尽可能多次地调用defineGetBalance(),只需传递要将该getBalance函数赋值给的对象即可。
// file2.js
const { defineGetBalance } = require('./file1');
// ...
defineGetBlance(obj1);
defineGetBlance(obj2);
// now both obj1 and obj2 have a getBalance() function
const balance1 = obj1.getBalance(id1)
const balance2 = obj2.getBalance(id2)
// you a for loop if you can
for (const obj of arrObj) {
defineGetBalance(obj);
}
// ...https://stackoverflow.com/questions/62687259
复制相似问题