ref – https://www.reddit.com/r/learnjavascript/comments/30mnra/tight_vs_loose_coupling_examples/
In JS, tight coupling between methods and objects in which if you were to change property name to say naaaaame,
then method sayName will not work.
1 2 3 4 5 6 |
var person = { name: "Jack", sayName: function() { alert(person.name); } }; |
Change from tight to loose
There is a tight coupling with Food and Fork. Because Fork was instantiated inside nomNomNom, you are forced to use a Fork for every Food.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function Food() {} Food.prototype.nomNomNom = function() { var utencil = new Fork(); console.log('Noms with ' + utencil.getType()); }; function Fork() {} Fork.prototype.getType = function() { return 'fork'; }; var pasta = new Food(); pasta.nomNomNom(); // -> Noms with fork |
Let’s correct it by using a parameter object to pass in whatever tool we need to use. This way, we inject whatever tool we need into the eating function.
The only thing we need to make sure is that the tool has a getType function and conforms to a common interface. That way, we can get the name of the tool.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function Food() {} // create Food constructor function // prototype function takes in utencil as parameter Food.prototype.nomNomNom = function(utencil) { console.log('Noms with ' + utencil.getType()); }; function Fork() {} // create Fork constructor function // prototype function getType is satisfied Fork.prototype.getType = function() { return 'fork'; }; function Spoon() {} // create Spoon constructor function // prototype function getType is satisfied Spoon.prototype.getType = function() { return 'spoon'; }; // create the food, and inject Spoon object var soup = new Food(); var spoon = new Spoon(); soup.nomNomNom(spoon); // -> Noms with spoon // create the food and inject Fork object var pasta = new Food(); var fork = new Fork(); pasta.nomNomNom(fork); // -> Noms with fork |