Last active
March 28, 2016 04:11
-
-
Save codejets/72d0c64438f62ce9d8ea to your computer and use it in GitHub Desktop.
Constructor Pattern Implementation
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
/* We will use an IIFE wrapping-function to keep the global scope clean and | |
to prevent things from being created in the global scope. We will use strict mode in a controlled enviroment, | |
also without triggering it in the global scope. */ | |
var Todo = (function() { | |
'use strict'; | |
function todo(name) { | |
// Enforces NEW even if called as an function | |
if (!(this instanceof todo)) { | |
return new todo(); | |
} | |
// Adds the name of the object created and returned to the passed name. | |
this.name = name; | |
// By default completed is set to false. | |
this.completed = false; | |
} | |
/* Unlike constructor function todo() prototype methods are not initialized | |
to every single instance of object created.*/ | |
todo.prototype.complete = function() { | |
console.log('Completed!'); | |
this.completed = true; | |
} | |
/* This method is just loaded once and all objects are linked to it. | |
So all instances have access to this method but not copies of it. */ | |
todo.prototype.toString = function() { | |
return this.name; | |
} | |
/* Return Object in case you are booting it as module in | |
something like an angular application */ | |
return todo; | |
}()); | |
// Testing Module | |
var t1 = new todo('Fix bug #2342'); | |
var t2 = new todo('Feature #23'); | |
var t3 = new todo('Call XYZ'); | |
t1.complete(); | |
console.log(t1); | |
t1.toString() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment