Monday, 19 September 2016

javascript - Does this way of defining JS objects have any purpose?



I'm maintaining some legacy code and I've noticed that the following pattern for defining objects is used:



var MyObject = {};


(function (root) {

root.myFunction = function (foo) {
//do something
};

})(MyObject);


Is there any purpose to this? Is it equivalent to just doing the following?




var MyObject = {

myFunction : function (foo) {
//do something
};

};



I'm not about to embark in a holy quest to refactor the whole codebase to my likings, but I'd really like to understand the reason behind that roundabout way of defining objects.



Thanks!


Answer



It's called the module pattern http://toddmotto.com/mastering-the-module-pattern/



The main reason is for you to create truly private methods and variables. In your case, it's not meaningful because it's not hiding any implementation details.



Here's an example where it makes sense to use the module pattern.




var MyNameSpace = {};

(function(ns){
// The value variable is hidden from the outside world
var value = 0;

// So is this function
function adder(num) {
return num + 1;
}


ns.getNext = function () {
return value = adder(value);
}
})(MyNameSpace);

var id = MyNameSpace.getNext(); // 1
var otherId = MyNameSpace.getNext(); // 2
var otherId = MyNameSpace.getNext(); // 3



Whereas if you just used a straight object, adder and value would become public



var MyNameSpace = {
value: 0,
adder: function(num) {
return num + 1;
},
getNext: function() {
return this.value = this.adder(this.value);

}
}


And you could break it by doing stuff like



MyNameSpace.getNext(); // 1
MyNameSpace.value = 0;
MyNameSpace.getNext(); // 1 again
delete MyNameSpace.adder;

MyNameSpace.getNext(); // error undefined is not a function


But with the module version



MyNameSpace.getNext(); // 1
// Is not affecting the internal value, it's creating a new property
MyNameSpace.value = 0;
MyNameSpace.getNext(); // 2, yessss
// Is not deleting anything

delete MyNameSpace.adder;
MyNameSpace.getNext(); // no problemo, outputs 3

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...