Just started out learning js and using the book Javascirpt an Absolute Beginner's Guide. Question is from an example in the book:
var awesomeSauce = (
function () {
var secretCode = "Zorb!";
function privateCheckCode(code) {
if (secretCode == code) {
alert("You are awesome!");
} else {
alert("Try again!");
}
}
// the public method we want to return
return {
checkCode: privateCheckCode
};
})();
Question is how do I go about to call this code?
awesomeSauce("Zorg!");
doesnt work and neither does
awesomeSauce().privateCheckCode("Zorg!");
Just started out learning js and using the book Javascirpt an Absolute Beginner's Guide. Question is from an example in the book:
var awesomeSauce = (
function () {
var secretCode = "Zorb!";
function privateCheckCode(code) {
if (secretCode == code) {
alert("You are awesome!");
} else {
alert("Try again!");
}
}
// the public method we want to return
return {
checkCode: privateCheckCode
};
})();
Question is how do I go about to call this code?
awesomeSauce("Zorg!");
doesnt work and neither does
awesomeSauce().privateCheckCode("Zorg!");
Share
Improve this question
asked Dec 16, 2016 at 9:00
BjathrBjathr
932 silver badges10 bronze badges
4 Answers
Reset to default 5awesomeSauce.checkCode("Zorg!");
The IIFE returns an object with the checkCode
property, that property is the (private) function.
The point of the IIFE is that this scopes the variables and functions within, so that they are not accessible from outside (e.g. privateCheckCode
and secretCode
exist only inside the IIFE).
Think of the returned object as an "export" of selected values or functionality.
var awesomeSauce = (
function () {
var secretCode = "Zorb!";
function privateCheckCode(code) {
if (secretCode == code) {
alert("You are awesome!");
} else {
alert("Try again!");
}
}
// the public method we want to return
return (
privateCheckCode
);
})();
awesomeSauce('Zorb!')
hey i don't know much but i happened to solve this: return statement return an expression not a code block. just go through the code i guess you will understand
Agree with Lucero's answer
1) The IIFE gets executed
2) result of the execution gets assigned to awesomeSauce
So what is the result of execution ?
It is whatever the function returned, below code
return {
checkCode: privateCheckCode
};
In this case, it returns an object with a property named "checkCode" which refers to inner function "privateCheckCode".
In short, it bees,
awesomeSauce = {
checkCode: privateCheckCode
};
Therefore, you can call your function like this awesomeSauce.checkCode("Zorb!");
You can call it with console.log(awesomeSauce.checkCode('Zorb!'));
as the iife returns an object which has checkCode key and the privateCheckCode as the value.