Constructor Pattern Example
Prototype
Prototype is an encapsulation of properties that an object links to.
Prototype helps when we do not want to copy the complete function while creating an object.
ES5
var Task = function (name) {
this.name = name;
this.completed = false;
}
Task.prototype.complete = function () {
console.log('completing task: ' + this.name);
this.completed = true;
};
Task.prototype.save = function () {
console.log('saving Task: ' + this.name);
};
var task1 = new Task('create a demo for constructors');
var task2 = new Task('create a demo for modules');
var task3 = new Task('create a demo for singletons');
var task4 = new Task('create a demo for prototypes');
task1.complete();
task2.save();
task3.save();
task4.save();
ES6
class Task {
constructor(name) {
this.name = name;
this.completed = false;
};
complete() {
console.log('completing task: ' + this.name);
this.completed = true;
};
save() {
console.log('saving Task: ' + this.name);
};
}
var task1 = new Task('create a demo for constructors');
var task2 = new Task('create a demo for modules');
var task3 = new Task('create a demo for singletons');
var task4 = new Task('create a demo for prototypes');
task1.complete();
task2.save();
task3.save();
task4.save();