DRAG DROP
You are developing a shared library to format information. The library contains a method
named _private.
The _private method must never be called directly from outside of the shared library.
You need to implement an API for the shared library.
How should you complete the relevant code? (Develop the solution by selecting the required
code segments and arranging them in the correct order. You may not need all of the code
segments.)
Answer: See the explanation
* Here there is a basic example:
// our constructor
function Person(name, age){
this.name = name;
this.age = age;
};
// prototype assignment
Person.prototype = (function(){
// we have a scope for private stuff
// created once and not for every instance
function toString(){
return this.name + ” is ” + this.age;
};
// create the prototype and return them
return {
// never forget the constructor …
constructor:Person,
// “magic” toString method
toString:function(){
// call private toString method
return toString.call(this);
}
};
})();
* Example:
You can simulate private methods like this:
function Restaurant() {
}
Restaurant.prototype = (function() {
var private_stuff = function() {
// Private code here
};
return {
constructor:Restaurant,
use_restroom:function() {
private_stuff();
}
};
})();
var r = new Restaurant();
// This will work:
r.use_restroom();
// This will cause an error:
r.private_stuff();
function getFormatter() {
var _private = function(input) {
alert(input + 10);
return input + 10;
}
return {
parseValue: function (input) {
return _private(input);
}
}
}
Can someone help with explanation to understand this better?
closures. The answer is wrong.
Correct one:
return {
parseValue: function (input) {
return _private(input);
}
“The _private method must never be called directly from outside of the shared library.” …this is a huge clue.
This means the _private function has to be “private” to use OOP terminology. JavaScript doesn’t implement access modifiers (public, private, protected, etc) …
JavaScript uses closures in order to ‘implement’ access modifiers…
to make function _private … private… it needs to ‘hide’ within another function…
that’s the JavaScript way 😉
So the answer is wrong, the right is:
Box 1: function getFormatter() {
Box 2: var _private = function(input) { return custom(data) }
Box 3: return { parseVaue: function (input){ return _private}; }
Box 4: }
Note: