I’ve got a module object that I want to clone and then override a function for.
var Module1 = (function () {
var hello = "hi there!";
return {
sayHello : function () {
console.log(hello);
}
}
})();
var Module2 = (function (old) {
var my = {}, key;
for (key in old) {
if (old.hasOwnProperty(key)) {
my[key] = old[key];
}
}
my.sayHello = function () {
console.log(old.hello + " again");
}
return my;
}(Module1));
Is there a way to access the ‘private’ variable ‘hello’ from the submodule? Calling Module2.sayHello() (on the code shown above) prints undefined again!.
No, you can’t.
You can add
into Module1’s return block, in this case you expose a public function which reuturn’s Module1’s private vairable hello.