我有一个包含属性值作为函数名的对象。这是我的对象bitbake core-image-minimal
:
obj
像这样运行对象属性值。
var obj = {
beforeCalc: beforeCalc,
calcEcn: calcEcn
};
function beforeCalc() {
console.log("beforeCalcMethodExecuted");
}
function calcEcn() {
console.log("calcEcnMethodExecuted");
}
为什么它会返回function runMethodsFromObj() {
for (var i in obj) {
console.log(i); // beforeCalc, calcEcn
console.log(i()); //i is not defined
}
}
runMethodsFromObj();
?
答案 0 :(得分:1)
for-in
循环为您提供对象的keys
和not their value
var obj = {
beforeCalc: beforeCalc,
calcEcn: calcEcn
};
function beforeCalc() {
console.log("beforeCalcMethodExecuted");
}
function calcEcn() {
console.log("calcEcnMethodExecuted");
}
function runMethodsFromObj() {
for (var i in obj) {
console.log(i); // beforeCalc, calcEcn
console.log(typeof i); // string
obj[i](); // Executes the stored function
}
}
runMethodsFromObj();