基于作为属性值给出的对象执行函数

时间:2018-06-13 10:43:54

标签: javascript oop

我有一个包含属性值作为函数名的对象。这是我的对象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();

1 个答案:

答案 0 :(得分:1)

for-in循环为您提供对象的keysnot 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();