-
Notifications
You must be signed in to change notification settings - Fork 0
Home
This repository is part of a larger project!
In Javascript, it should be possible to redefine a function whithin an another function. It is important to know that the new defined function should only be usable within the scope of that function which contains the new definition. For a better understanding an example shall follow:
function outerFunction()
{
return "Outer function";
}
function anotherFunction()
{
//Redefining
function outerFunction()
{
return "Redefined function";
}
console.log(outerFunction());
}
anotherFunction(); //Outputs "Redefined function"
console.log(outerFunction()); //Outputs "Outer function"
In addition, redefining a function within a block(e.g. within a if statement) should not work like expected in other languages, because Javascript does not support block scoping (NOT COMPLETELY TRUE).
The problem in this example is that the first definition of outerFunction once redefined, could not be used within anotherFunction. This could lead to flawed behaviour of a system.
To prevent this, a solution could be as follows:
function outerFunction()
{
return "Outer function";
}
function anotherFunction()
{
var innerFunction = outerFunction;
//Redefining
innerFunction = function()
{
return "Redefined function";
}
console.log(innerFunction());//Outputs "Redefined function"
console.log(outerFunction());//Outputs "Outer function"
}
anotherFunction();
The essential change in the code seen above is
var innerFunction = outerFunction;
This should be self-explanatory.
The user interaction part should look like the content as seen below by starting "index.html" in a web browser.
The program has two buttons:
-
"WORKING" shows how it should be done
-
"BROKEN" shows a possible bug which incorrect implementation could cause
Note that all files should be placed in the same folder so that the functionality of the code is guaranteed.
This knowledge was gained:
Effective JavaScript "68 Specific Ways to Harness the Power of JavaScript" by David Herman