[英]Execute functions based on object given as property value
I have an object containing property values as function names. 我有一个包含属性值作为函数名称的对象。 This is my object
obj
: 这是我的对象
obj
:
var obj = {
beforeCalc: beforeCalc,
calcEcn: calcEcn
};
function beforeCalc() {
console.log("beforeCalcMethodExecuted");
}
function calcEcn() {
console.log("calcEcnMethodExecuted");
}
Running the objects property values like this. 像这样运行对象的属性值。
function runMethodsFromObj() {
for (var i in obj) {
console.log(i); // beforeCalc, calcEcn
console.log(i()); //i is not defined
}
}
runMethodsFromObj();
Why is it returning undefined
? 为什么返回
undefined
?
The for-in
loop gives you the keys
of the object and not their value
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.