Before es6, JavaScript doesn’t support the concept of classes but it does support special constructor functions that work with objects.
By simply prefixing a call to a constructor function with the keyword “new”, we can tell JavaScript we would like the function to behave like a constructor and instantiate a new object with the members defined by that function.
Inside a constructor, the keyword this references the new object that’s being created. Revisiting object creation, a basic constructor may look as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function Car( model, year, miles ) { this.model = model; this.year = year; this.miles = miles; this.toString = function () { return this.model + " has done " + this.miles + " miles"; }; } // Usage: // We can create new instances of the car var civic = new Car( "Honda Civic", 2009, 20000 ); var mondeo = new Car( "Ford Mondeo", 2010, 5000 ); // and then open our browser console to view the // output of the toString() method being called on // these objects console.log( civic.toString() ); console.log( mondeo.toString() ); |
Constructors With Prototypes
Functions, like almost all objects in JavaScript, contain a “prototype” object. When we call a JavaScript constructor to create an object, all the properties of the constructor’s prototype are then made available to the new object. In this fashion, multiple Car objects can be created which access the same prototype. We can thus extend the original example as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function Car( model, year, miles ) { this.model = model; this.year = year; this.miles = miles; } // Note here that we are using Object.prototype.newMethod rather than // Object.prototype so as to avoid redefining the prototype object Car.prototype.toString = function () { return this.model + " has done " + this.miles + " miles"; }; // Usage: var civic = new Car( "Honda Civic", 2009, 20000 ); var mondeo = new Car( "Ford Mondeo", 2010, 5000 ); console.log( civic.toString() ); console.log( mondeo.toString() ); |
Above, a single instance of toString() will now be shared between all of the Car objects.
Circular List example
In the example below, we declare a ListNode constructor function so that we can instantiate objects from it,
We instantiate different ListNode objects and link them together in constructor function List. The linking happens because each ListNode has a next and previous.
List has 4 public properties:
– head
– tail
– now
– listName
Head, tail, now all point to different parts of the list.
The list uses prototype functions insert, remove, display so users can enter, remove, and display data from the list.
Thus, all instantiations of constructor function List use these prototype functions.
https://stackoverflow.com/questions/24488196/revealing-module-prototype-pattern
PRO – This saves a lot of memory because say we create 2 List instantiations called metro and gallery. There will be 2 copies of these functions for each instantiation. However, if we are to use prototype, there is only 1 instance of all these functions. And both metro and gallery will call that 1 instance.
In other words, the benefit of the prototype is that its properties are shared amongst all instances. This means that it’s static, not instance-specific.
CON – If you want to use the prototype, you cannot access truly private variables; you will need to use public properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
var StepEnum = Object.freeze({NEXT: "step next", PREV: "step previous"}); function ListNode(newData, newPrev, newNext) { // this = {} if (new.target === undefined) { console.log('You didnt use new. Giving you a new Node Object'); return new Node(); } // public properties this.data = newData; this.next = newNext; this.prev = newPrev; // public functions this.clean = function() { this.data = null; this.next = null; this.prev = null; } this.display = function() { console.log("[" + this.data + "]") } // return this } // List Node function List(newName) { this.head = null; this.tail = null; this.now = null; this.listName = newName; // private // O(1) this.removeLastNode = function(data, ref) { if (this.dataMatches(data.toUpperCase(), ref.data.toUpperCase())) { if (this.head === this.tail) { this.head = this.head.next = this.head.prev = null; this.tail = this.tail.next = this.tail.prev = null; ref.clean(); return true; } } return false; } // private this.removeNodeAtHead = function(ref) { if (ref === this.head) { var temp = ref; ref.next.prev = this.tail; ref.prev.next = ref.next; this.head = ref.next; temp.clean(); return true; } return false; } // private // O(1) this.removeNodeAtTail = function(ref) { if (ref === this.tail) { var temp = ref; ref.next.prev = ref.prev; ref.prev.next = ref.next; this.tail = ref.prev; temp.clean(); return true; } return false; } // private // O(1) this.removeNodeInBetween = function(ref) { if ((ref !== this.tail) && (ref !== this.head)) { ref.next.prev = ref.prev; ref.prev.next = ref.next; ref.clean(); return true; } return false; } } List.prototype.about = function() { console.log(`Circular list (${this.listName}) with nodes that reference next and previous. Ricky Tsao 2018`); } List.prototype.current = function() { return this.now; } List.prototype.setCurrentToHead = function() { this.now = this.head; return this.now; } List.prototype.setCurrentToTail = function() { this.now = this.tail; return this.now }; List.prototype.step = function(steps, StepEnum) { if(!isNaN(steps) && steps > 0) { while (steps > 0) { this.now = (StepEnum.NEXT) ? this.now.next : this.now.prev; steps--; } } } List.prototype.isEmpty = function() { return (!this.head && !this.tail); } List.prototype.insert = function(data) { console.log("PROTOTYPE - Inserting data: " + data); try { if (!this.isString(data)) throw "Data Must be a String"; if (this.isEmpty()) { this.head = new ListNode(data, null, null); this.tail = this.head; } else { this.tail = new ListNode(data, this.tail, this.head); this.tail.prev.next = this.tail; this.head.prev = this.tail; } this.now = this.tail; } catch(err) { console.log("\n------ ERROR ------"); console.log("description: data not entered"); console.log("reason: " + err); console.log("===================\n\n") } } // Notice that in our prototype, we can use private functions from List // public // O(n) List.prototype.remove = function(data) { if (this.isEmpty()) { console.log("Nothing to remove because list is empty"); return; } try { var traversal = this.head; if (this.removeLastNode(data, traversal)) { return;} do { if (this.dataMatches(data.toUpperCase(), traversal.data.toUpperCase())) { if (this.removeNodeAtHead(traversal)) return; if (this.removeNodeAtTail(traversal)) return; if (this.removeNodeInBetween(traversal)) return; } traversal = traversal.next; } while (traversal != this.head); } catch(error) { console.log("Warning: "+ error); } }; List.prototype.dataMatches = function(data1, data2) { return (data1.toUpperCase() === data2.toUpperCase()); } List.prototype.isString = function(data) { return ((typeof data) === 'string'); } List.prototype.display = function() { console.log("PROTOTYPE - display CircularList: " + this.listName) if (this.isEmpty()) { console.log("-- LIST (" + this.listName + ") IS EMPTY --"); return; } var traversal = this.head; console.log("-----" + this.listName + "-----"); do { traversal.display(); traversal = traversal.next; } while (traversal !== this.head && traversal != null); console.log("===============") } var metro = new List("metro"); metro.about(); metro.insert("Hou Hai"); metro.insert("Keyuan"); metro.insert("Window of the World"); metro.display(); metro.remove("Window of the World"); metro.display(); metro.remove("Hou Hai"); metro.display(); metro.remove("Window of the World"); metro.display(); metro.remove("Shui wan"); metro.display(); metro.remove("Keyuan"); metro.display(); |