Last active
September 29, 2015 13:36
-
-
Save saltukalakus/acd76001ffcdae99e1f3 to your computer and use it in GitHub Desktop.
Structural patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test = require('tape'); | |
// Basic module with closure | |
var Module = (function () { | |
var my = {}, | |
privateVariable = 1; | |
function setPrivateMethod(val) { | |
privateVariable = val; | |
} | |
my.publicVariable = 1; | |
my.moduleSetPrivateMethod = function (val) { | |
setPrivateMethod(val); | |
}; | |
my.moduleGetMethod = function () { | |
return("private: " + privateVariable + " public: " + this.publicVariable); | |
}; | |
return my; | |
}()); | |
Module.moduleGetMethod(); | |
// Extend the module with a new name space (Augmentation) | |
var newModule = ( function (module) { | |
module.newNameSpace = { | |
"foo": function () { | |
return("This is foo"); | |
}, | |
// Call a base module function from new module | |
"call_base": function() { | |
return module.moduleGetMethod(); | |
} | |
}; | |
return module; | |
})(Module); | |
test('extended module function call', function(t) { | |
t.equal(newModule.newNameSpace.foo(), "This is foo", "can call the extended new function"); | |
t.equal(newModule.moduleGetMethod(), "private: 1 public: 1", "extended module initial variables same"); | |
t.end(); | |
}). | |
test('new module reference the initial module', function(t) { | |
Module.moduleSetPrivateMethod(5); | |
t.equal(newModule.moduleGetMethod(), "private: 5 public: 1", "private variable is common"); | |
Module.publicVariable = 10; | |
t.equal(newModule.moduleGetMethod(), "private: 5 public: 10", "public variable is common"); | |
t.end(); | |
}); | |
test('call a function from base module in the extended module', function(t) { | |
t.equal(newModule.newNameSpace.call_base(), "private: 5 public: 10", "can call base module function from extended module."); | |
t.end(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment