JavaScript Prototyping Techniques September 3rd, 2013

Prototyping via Constructor Functions

/* Old way - awkward - exists for people used to classes */
// Create constructor function
function Greeter(name){
    this.name = name || 'JohnDoe';
}
// Attach to that constructor function's prototype property
Greeter.prototype.hello = function hello(){
    return 'Old Way = Hello, my name is ' + this.name;
}
// Instantiate new object with the 'new' keyword
var old = new Greeter('Old Way');
console.log(old.hello(Greeter.name));

Prototyping via JavaScript Object.create()

// Create your prototype
var proto = {
    hello: function hello(){
        return 'New #1 = Hello, my name is ' + this.name;
    }
};
// Pass that prototype into Object.create
var extension = Object.create(proto);
// Set whatever you want on that object because JavaScript has dynamic object extension
extension.name = 'New Extension Way';
console.log(extension.hello(extension.name));

Prototyping via Cloning/Concatenation

// Create object literal
var proto2 = {
    hello: function hello() {
        return 'New #2 = Hello, my name is ' + this.name;
    },
    name: 'default'
};
// Add new properties by cloning/extending object literal
// Also, properties can be overwritten (defaults & overrides)
// _.extend(destination, *sources)
var mixin_style = _.extend({}, proto2, {name: 'New Mixin Way'});
console.log(mixin_style.hello(mixin_style.name));
console.log(proto2.name + ' vs. ' + mixin_style.name);