How do I execute particular function through this function

Hi guys,
I want to fire function b or c via the route of function x below:

function x(obj){
	Object.keys(obj).forEach(function (fn) {
		if (typeof obj[fn] === 'function') {
			return obj[fn].apply(this, arguments);
		}
	});
}

var a = {
	b: function() {
		console.log("Function B fired!");
	},
	c: function() {
		console.log("Function C fired!");
	}
};

x(a);

The command fires all the functions at once. I want it to fire only one at the time. How do I do that?
Note that I don’t want to fire it this way:

 a.b(); || a.c();

Thank you,

How would you want to fire one or the other via the x function. By passing another parameter to the x function to specify the one that you want to fire? For example:

x(a, 'b');

Something like that? Or do you have something else in mind?

Hi Paul,
Thank you. It isn’t work.
I just want to make sure that function executed this way is error-free.
You put try and catch in the function with error would ignore and the rest would run normally. So the process would not interrupt from the function that is error.

Without this, if function b has an error it would stop and function c would never fire. Like this:

function x(obj){
    Object.keys(obj).forEach(function (fn) {
        if (typeof obj[fn] === 'function') {
            try {
                return obj[fn].apply(this, arguments);
            } catch (ex) {
                console.log(fn, "(): " + ex.message);
            }
        }
    });
}

Thank you,

So, basically you want to run each function within an object? Try this:

function x(obj){
	for(prop in obj){
		if(typeof obj[prop] === 'function'){
			obj[prop].apply(this, arguments)
		}
	}
}

var a = {
	b: function() {
		console.log("Function B fired!");
	},
	c: function() {
		console.log("Function C fired!");
	}
};
x(a);

Notice that I’m not returning anything in x()…otherwise b() would get run and not c(). If you’d like to return something, like “all passed” then you would have the return statement outside the for…in loop

Hi @labofoz,

Thank you. It appears to have worked.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.