Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Last active March 2, 2018 01:00
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 GreggSetzer/f0c271a5655e975b35b07f4ef64cd05c to your computer and use it in GitHub Desktop.
Save GreggSetzer/f0c271a5655e975b35b07f4ef64cd05c to your computer and use it in GitHub Desktop.
Javascript Interview Question: Constructor Pattern
/*
1. Use the constructor pattern for object creation using the new keyword.
2. Each instance of the object will have its own reference to this.
3. Link functions to the object using the prototype. This provides a
performance gain because functions aren't copied into each
instance of the object. They are linked to the prototype.
It's better to have one copy of functions around, not multiple copies.
Now, if we can use ES 2015 syntax:
1. Use the class keyword.
2. Move the constructor function logic to a function declaration called constructor.
3. Move functions inside the class declaration.
The constructor pattern is used to create new objects with its own scope. To use
the constructor pattern, we use the new keyword. The new keyword will:
1. Create a new object by linking to the object prototype.
2. It binds "this" to the new object scope.
3. Lastly, it implicitly returns "this". In other words, "this" is returned automatically.
Note:
Prototypes encapsulate properties that an object links to. By using prototypes, we avoid
a performance hit by copying functions into every instance.
*/
/* * * * * * * * * * * * * * * * * * * * * *
* Constructor Pattern Example
* * * * * * * * * * * * * * * * * * * * * */
var Task = function(name) {
this.name = name;
this.completed = false;
}
Task.prototype.save = function() {
console.log('Saving', this.name);
}
Task.prototype.complete = function() {
this.completed = true;
console.log(this.name + ' is completed.');
}
var task1 = new Task('Task 1');
var task2 = new Task('Task 2');
task1.save();
task1.complete();
task2.save();
task2.complete();
/* * * * * * * * * * * * * * * * * * * * * *
* ES 2015 Constructor Pattern Example
* * * * * * * * * * * * * * * * * * * * * */
class Task {
constructor(name) {
this.name = name;
this.completed = false;
}
complete() {
console.log('Completed', this.name);
this.completed = true;
}
save() {
console.log('Saving', this.name);
}
}
let task3 = new Task('Learn design patterns');
task3.save();
task3.complete();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment