In Javascript the syntax a.b
can be replaced with a["b"]
. So in your case you can use
window["funcOne"](target)["funcTwo"](x, y, z);
where of course it makes sense only if you are using variables instead of "funcOne"
and "funcTwo"
.
If everything is instead fixed but you simply want to delay execution you can use "thunking" with an anonymous closure with
x = function(){ return funcOne(target).funcTwo(x, y, z); };
and then you can evaluate with x()
to get the desired result later.
The last example will work correctly even if the variables target
and x
, y
and z
are local to the enclosing scope because the thunking closure will "capture" them.
You should however pay attention to the fact that in Javascript the only way to create a new scope is to use a function (a block surrounded with {
and }
is NOT a scope like happens in C++ and other languages).
If you need to create several closures in a loop this can bite back and is a source of a quite common mistake...
for (var i=0; i<options.length; i++)
{
var menu_item = document.createElement("div");
menu_item.textContent = "Option " + i;
menu_item.onclick = function () {
// Warning this will NOT work. All divs will
// alert using the same number!
alert("Option " + i + " selected");
}
menu.appendChild(menu_item);
}
here I used a closure for the onclick
event on the div, but this is not going to work because all those functions will use the very same i
variable. Because in Javascript the only way to create a scope is using a function the solution is:
for (var i=0; i<options.length; i++)
{
var menu_item = document.createElement("div");
menu_item.textContent = "Option " + i;
(function(i){
menu_item.onclick = function () {
alert("Option " + i + " selected");
};
})(i); // Pass current `i` as parameter
menu.appendChild(menu_item);
}
This way the variable i
inside the onclick
handler will be different for each closure.
This pattern of creating a function just to call it immediately is often used in Javascript when you need to create many independent closures so it's better to know and understand it.