Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Forked from max-mapper/index.js
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/eb7ed0a5551d071702d0 to your computer and use it in GitHub Desktop.
Save joyrexus/eb7ed0a5551d071702d0 to your computer and use it in GitHub Desktop.
Prototype vs object style

Prototype style

function Person(first, last) {
    this.first = first;
    this.last = last;
}

Person.prototype.greet = function () {

    console.log('Hello', this.first, this.last + '!');
};

var bob = new Person('Bob', 'Jones');
bob.greet(); // Hello Bob Jones!

Object style

function person(first, last) {

    return {
        first: first,
        last:  last,
        greet: function () {
            console.log('Hello', first, last + '!');
        }
    };
}

var bob = person('Bob', 'Jones');
bob.greet(); // Hello Bob Jones!

Reference

// prototype style (more advanced)
function DB() {}
DB.prototype.open = function() {}
DB.prototype.close = function() {}
DB.prototype.query = function() {}
function connectToDB() {
return new DB()
}
// object style (simpler)
function connectToDB() {
return {
open: function() {},
close: function() {},
query: function() {}
}
}
// with both the external API is the same
var db = connectToDB()
db.open()
db.query()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment