Reputation: 8695
Fiddle here
I'm looking at making some very high level logic into helper functions for curiosity's sake. I would like to be able to execute a function with its parameters in the _if
function without having to define something like _callback
ahead of time? I feel like I'm missing something here.
var _if = function(predicate,callback){
if(predicate){
callback(); //callback(arguments) is not arguments for callback
}
};
var text = 'some text';
_if(1 > 0,function(){
console.log('hello world'); //hello world
});
_if(1 > 0,function(text){
console.log(text); //undefined
});
//define callback for this situation
var _callback = function(x){
console.log(x);
}
_if(1 > 0,function(){
_callback(text); //some text
});
Upvotes: 0
Views: 82
Reputation:
Not sure what you want, but maybe this helps:
You can call your function like this too:
_if(1 > 0,_callback.bind(null,text)); //null is the value of this
_if(1,function(text){
console.log(text); //this way not undefined
}.bind(null,text));
1) This works because of the logic of JavaScript. In further versions you can use your version too if you use let text = 'some text';
- ref
2) null
is the this value for the function, (more info here) but I think you can pass this
too if you need to use it in the function (null
will be automatically replaced in non-strict mode to the global object. That's why you can use window.colsole.log
inside the function. - ref)
Upvotes: 1
Reputation: 46183
Why not just take the arguments to the callback function as extra parameters on _if
?
var _if = function (predicate, callback, context) {
if (predicate) {
var callbackArgs = [].slice.call(arguments, 3);
callback.apply(context || null, callbackArgs);
}
};
// Usage:
_if(true, console.log, console, "text");
Upvotes: 1