开发者

How can I call javascript function using a foreach on a JSON object?

开发者 https://www.devze.com 2023-02-10 02:45 出处:网络
My problem is pretty easy to understand. I have a JSON object (see code) and I will automatically call all functions of this object in the order that those appears. .

My problem is pretty easy to understand. I have a JSON object (see code) and I will automatically call all functions of this object in the order that those appears.

.

var installer = {
    a : function() {
          ...
        }
    b : function() {
          ...
        }
};

for(var func in installer) {
    fn.call(document);
};
开发者_如何转开发

Have you any idea why the previous code doesn't work ? I'm sorry, I'm a beginner in javascript.

Thanks in advance !

Regards.


You don't have a variable called fn, and you are also missing commas at the end of your function definitions.

Additionally, your functions will not be called in order because JavaScript orders your object properties arbitrarily. You may want to consider using an array or, as I have done below, specify an array that determines the order.

var installer = {
    a : function() {
          ...
        },
    b : function() {
          ...
        },
};

var order = [ "a", "b" ];

for(var i = 0; i < order.length; i++) {
    installer[order[i]].call(document);
}


You declare var func as the variable to loop through the members of installer, yet you use fn.call(...). Where did fn come from?

Should you be able to do: installer[func].call(document) instead of fn.call(document).

Also your functions declared in the installer object don't take any arguments, yet you're passing document as an argument.

[updated code to add missing .call to installer[func](document)]

0

精彩评论

暂无评论...
验证码 换一张
取 消