Reputation: 1357
Is there a way to bind the same 'this' context to different functions?
var obj = {'a':1, 'b':2 };
init.call(obj);
function init()
{
func1.call(this);
func2.call(this);
func3.call(this);
etc...
}
Preferred syntax:
function init()
{
// each function should use this.
func1();
func2();
func3();
etc...
}
Not really a problem per se, just syntactic sugar and DRY; thanks in advance.
Edit: Thanks to Barmar, I came up with this:
[ func1, func2, etc... ].forEach( function(func){ func.call(this); }.bind(this));
Upvotes: 0
Views: 46
Reputation: 780909
You could write a function that does it:
function callAll() {
var funcArray = Array.prototype.slice.call(arguments);
for (var i = 0; i < funcArray.length; i++) {
funcArray[i].call(this);
}
}
Then you can do:
callAll.call(obj, func1, func2, func3);
Upvotes: 1