Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alvieirajr/a4e85363a37ed39acb99e38fab443887 to your computer and use it in GitHub Desktop.
Save alvieirajr/a4e85363a37ed39acb99e38fab443887 to your computer and use it in GitHub Desktop.
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("noone@example.com", "I can send email from my phone!");
@alvieirajr
Copy link
Author

This is a functional pattern example for inheritance as explained in Douglas Crockford's JavaScript: The Good Parts.

@alvieirajr
Copy link
Author

Drawbacks to the functional pattern

  1. 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.
  2. Methods cannot be inlined
  3. Superclass methods cannot be renamed (or will be renamed incorrectly)
  4. Types cannot be tested using instanceof

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment