This is from an example in YDKJS Scope & Closures:
var foo = (function CoolModule(id) {
function change() {
// modifying the public API
publicAPI.identify = identify2;
}
function identify1() {
console.log(id);
}
function identify2() {
console.log(id.toUpperCase());
}
var publicAPI = {
change: change,
identify: identify1
};
return publicAPI;
})("foo module");
foo.identify(); // foo module
foo.change();
foo.identify(); // FOO MODULE
Inside of the function change()
, I'm modifying the content of the returned object by assigning a different function to the "identify" key. Indeed, I can change the value of any key to any value like this: for example, publiAPI.change = null;
I can even add new properties this way, e.g., publicAPI.newFunc = function(){console.log("hi");}
. However, I cannot do publicAPI = {}
or set the publicAPI object itself, e.g., publicAPI = {a: 1}
. Why is this the case? Is there a way to modify the object itself?
I can even use the delete operator to delete properties.