Created
July 15, 2016 13:08
-
-
Save alvieirajr/a4e85363a37ed39acb99e38fab443887 to your computer and use it in GitHub Desktop.
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
var sendMessage = function(a,b) { | |
console.log('Message sent to: ' + a + ', content: ' + b); | |
}; | |
var phone = function(spec) { | |
var that = {}; | |
that.getPhoneNumber = function() { | |
return spec.phoneNumber; | |
}; | |
that.getDescription = function() { | |
return "This is a phone that can make calls."; | |
}; | |
return that; | |
}; | |
var smartPhone = function(spec) { | |
var that = phone(spec); | |
spec.signature = spec.signature || "sent from " + that.getPhoneNumber(); | |
that.sendEmail = function(emailAddress, message) { | |
// Assume sendMessage() is globally available. | |
sendMessage(emailAddress, message + "\n" + spec.signature); | |
}; | |
var super_getDescription = that.getDescription(); | |
that.getDescription = function() { | |
return super_getDescription() + " It can also send email messages."; | |
}; | |
return that; | |
}; | |
var myPhone = phone({"phoneNumber": "8675309"}); | |
var mySmartPhone = smartPhone({"phoneNumber": "5555555", "signature": "Adios"}); | |
mySmartPhone.sendEmail("[email protected]", "I can send email from my phone!"); |
Drawbacks to the functional pattern
- Instances of types take up more memory:
Every time phone() is called, two new functions are created (one per method of the type). Each time, the functions are basically the same, but they are bound to different values. - Methods cannot be inlined
- Superclass methods cannot be renamed (or will be renamed incorrectly)
- Types cannot be tested using instanceof
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a functional pattern example for inheritance as explained in Douglas Crockford's JavaScript: The Good Parts.