- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Call function with function parameter
hii ,
i want to call function with function parameter …
if ( bool ) {
myfunc('right');
}
else {
myfunc('left');
}
function myFunc(param){
var right = function(){
return 'right';
}
var left = function(){
return 'left';
}
param.call(param);
}
how can i do that? :( i dont want to use if else statement
var bool = false;
if ( bool ) {
myFunction('left');
}
else {
myFunction('right');
}
function left() {
console.log('left');
}
function right() {
console.log('right');
}
function myFunction( func ) {
var fn = window[func];
if ( typeof fn === 'function' ) {
fn();
}
}
thank you for answer.
can you explain what are window[func] function?
The window represents the JavaScript window object. It’s the global scope for all the JavaScript code that runs in the browser.
Function left
, right
and myFunction
are all in global space. Essentially it’s this:
window.left()
, window.right()
etc…
function myFunction( func ) {
// assign variable fn to window object
var fn = window[func];
// at this point fn = window.right
// we then check if the window.right is a function
if ( typeof fn === 'function' ) {
// if so run it
fn();
}
}
Hope that helps.
Alen