Last active
August 29, 2015 14:00
-
-
Save oprearocks/11500164 to your computer and use it in GitHub Desktop.
Object literal vs. constructor -- proof of concept
This file contains 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
/** | |
* Single object -- object literal | |
*/ | |
var db = { | |
host: 'localhost', | |
dbname: 'myDB', | |
credentials: { | |
username: 'dbuser', | |
password: 'dbpassword' | |
}, | |
connect: function() { | |
console.log( | |
'Connecting to %s with %s:%s on %s', | |
this.dbname, | |
this.credentials.username, | |
this.credentials.password, | |
this.host | |
); | |
}, | |
}; | |
/** | |
* Constructor | |
*/ | |
function DB(dbname, credentials, host) { | |
this.dbname = dbname; | |
this.host = host; | |
this.credentials = credentials; | |
} | |
DB.prototype.connect = function() { | |
console.log( | |
'Connecting to %s with %s:%s on %s', | |
this.dbname, | |
this.credentials.username, | |
this.credentials.password, | |
this.host | |
); | |
}; | |
var myNewDb = new DB('myDataBase', { | |
username: 'someuser', | |
password: 'somepass' | |
}, | |
'localhost'); | |
myNewDb.connect(); | |
var myOtherDb = new DB('myOtherDatabase', { | |
username: 'anotheruser', | |
password: 'anotherpass' | |
}, 'otherhostname'); | |
myOtherDb.connect(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment