xcode xcode - 7 months ago 7
Javascript Question

JS - Confusion on function that rewrite tyself

To all JS experts,
Im still trying to learn JS using books from Stoyan Stefanov (Object-Oriented JS).

Get stuck on page 83, where the following codes must work,



a = a(); // First Call
function a() {
alert('A');
a = function() { // I get this. Redefining functions.
alert('B');
};
}
a(); // Second Call





The book suggested that if we call/invoke for the 2nd time it would actually alert B after alert A occur.

However, instead of working it gives us TypeError: a is not a function after successfully alert A.

Whats the mistake here??

Thank You

Answer

The first line:

a = a();

calls the function and assigns its return value to a. But the function's return value is undefined - any function that doesn't explicitly return a value with return will implicitly return undefined (unless called with new, but you can ignore that here). So then on the last line when you say a() you are basically saying undefined(). And of course undefined is not a function.

Did the code in the book really say a = a();? Change it to a() and it'll work as expected.

Alternatively you could change the function to return the new function on the first call rather than overwriting a directly:

a = a(); // First Call
function a() {
 alert('A');
 // following line changed to return the new function instead
 // of assigning it to a immediately
 return function() { 
  alert('B');
 };
}
a(); // Second Call
Comments