Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Constructor Pattern
- * -------------------
- * Used to create a new object with its own scope.
- * You need a constructor function which when run with the new keyword will return
- * a new object.
- * The new keyword:
- * - Creates a new object
- * - Links the object to an Object prototype
- * - Binds this to the new object
- * - Returns this
- */
- function Task(title,description) {
- this.title = title;
- this.description = description;
- this.completed = false;
- this.getTitle = function() {
- return this.title
- }
- this.completeTask = function() {
- this.completed = true;
- console.log(`${this.title} has been completed.😁`)
- }
- }
- var buyApple = new Task('Buy Apples', 'Buy 5 Apples')
- console.log(buyApple)
- /*
- * One caveat of the constructor above is that all its functions will be replicated
- * for each of the instantiated tasks. if we have 100 tasks we'll have 100 getTitle()s
- * We can fix it using prototypes.
- * className.prototype.methodName = sharedFunction() { ... }
- */
- Task.prototype.getDetails = function () {
- return `${this.title} \n ${this.description}`
- } // All instantiated Tasks will link to 1 getDetails()
- /*
- * Module Pattern
- * --------------
- * Used to encapsulate a collection of similar functions/methods
- * Just an object with methods
- * If made using a function we can also have the ability to define private variables
- * that are only accessible from the methods.
- */
- // Repo is acolection of functions handling interactions with the DB
- var repo = function () {
- // DB config & setup
- let db = { ... }
- return {
- get: function(id) {
- console.log(`Getting task ${id}`);
- return {
- name: 'new task from db'
- }
- },
- save: function(task) {
- console.log(`Saving ${task.name} to the db`)
- }
- }
- }
- module.exports = repo()
- // To use this module in another file...
- var Repo = require(`path\to\module`)
- // We can then use the functions provided
- let taskFromRepo = Repo.get()
- Task.prototype.savr = function () {
- console.log(`Saving task: ${this.name}`);
- Repo.save(this);
- }
- Repo.save(taskFromRepo)
- /*
- * Factory Pattern
- * ---------------
- * Provides a common place for initializing objects
- */
- var repoFactory = function() {
- var repos = this;
- var repoList = [
- {name: 'task', source: 'path\to\repo'},
- {name: 'project', source: 'path\to\repo'},
- {name: 'user', source: 'path\to\repo'},
- ]
- repoList.forEach(function(repo) {
- repos[repo.name] = require(repo.source)()
- });
- }
- module.exports = new repoFactory;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement