Reputation: 331
I've mocked up some code here
var common = common || {};
(function(NAMESPACE) {
NAMESPACE = {
isIE: function() {
return true;
}
};
main();
})(common);
function main() {
console.log(common.isIE());
return 'Hello, World!';
}
I would like to understand a couple of things,
1) Why isn't this working, I guess it has something to do with how scoping is "decided" and IIFE, but not entirely sure.
2) How to make this code work?
Upvotes: 0
Views: 72
Reputation: 23798
When you are passing an object as an argument in JS, you should remember that you are passing "by-value" the reference of it.
Creating a new object in literal notation and assigning it to the argument like this,
NAMESPACE = {
isIE: function() {
return true;
}
};
can only point the argument to the new object - not to the object of the reference you passed the argument by.
If you had said,
NAMESPACE.isIE = function() {}
it would work.
Upvotes: 0
Reputation: 7742
common
which passed as argument named NAMESPACE
needs to be extended instead of assigning new value.
So Object.assign
can help here.
var common = common|| {};
(function(NAMESPACE) {
Object.assign(NAMESPACE,{
isIE: function() {
return true;
}
});
main();
})(common);
function main() {
console.log(common.isIE());
return 'Hello, World!';
}
Upvotes: 5