Last active
December 23, 2015 18:19
-
-
Save ryasmi/6674752 to your computer and use it in GitHub Desktop.
Treating classes and modules as functions (units) with dependencies. Shows that classes and modules can be defined in the same way, but used differently (like classes and modules).
This file contains hidden or 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
(this.myUnit = function myUnit() { | |
var self = {}; | |
self.myMethod = function () { | |
return 'hello world'; | |
}; | |
return self; | |
}).needs = { | |
// Has no dependencies. | |
}; |
This file contains hidden or 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
(this.testMyUnit = function testMyUnit() { | |
var self = {}; | |
var myUnit = testMyUnit.needs.myUnit; | |
self.run = function () { | |
var expectResult = 'hello world'; | |
var testModule = myUnit().myMethod() === expectResult; | |
var testNew = (new myUnit).myMethod() === expectResult; | |
var testCreate = Object.create(myUnit()).myMethod() === expectResult; | |
// Returns the number of failed tests. | |
return Number(!testModule) + Number(!testNew) + Number(!testCreate); | |
}; | |
return self; | |
}).needs = { | |
// Depends on myUnit. | |
myUnit: myUnit | |
}; | |
testMyUnit().run(); |
This file contains hidden or 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
(this.tryMyUnit = function tryMyUnit() { | |
var self = {}; | |
var myUnit = tryMyUnit.needs.myUnit; | |
self.run = function () { | |
// Using unit as a module. | |
console.log(myUnit()); | |
// Calling a method inside a unit being used as a module. | |
console.log(myUnit().myMethod()); | |
// Using unit to construct a new instance using new. | |
console.log(new myUnit); | |
// Calling a method on a new instance constructed by a unit using new. | |
console.log((new myUnit).myMethod()); | |
// Using unit to construct a new instance Object.create. | |
console.log(Object.create(myUnit())); | |
// Calling a method on a new instance constructed by a unit using Object.create. | |
console.log(Object.create(myUnit()).myMethod()); | |
}; | |
return self; | |
}).needs = { | |
// Depends on myUnit. | |
myUnit: myUnit | |
}; | |
tryMyUnit().run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment