Skip to content

Instantly share code, notes, and snippets.

@hwclass
Created April 16, 2017 14:33
Show Gist options
  • Save hwclass/a544879eaf8c18b82eca4d4dee4c9b1e to your computer and use it in GitHub Desktop.
Save hwclass/a544879eaf8c18b82eca4d4dee4c9b1e to your computer and use it in GitHub Desktop.
Class Creation Patterns
/*Functions by Delegations*/
var Car = function(loc) {
var obj = Object.create(Car.methods);
obj.loc = loc;
return obj;
};
Car.methods = {
move: function() {
this.loc++;
}
};
var amy = Car(1);
amy.move(); //loc becomes 2
amy.move(); //loc becomes 3
/*Prototypal Classes*/
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
return obj;
};
Car.prototype.move = function() {
this.loc++;
}
var amy = new Car(1);
amy.move(); //loc becomes 2
amy.move(); //loc becomes 3
/**/
Car.prototype.constructor; //Car
amy.constructor; //Car
/**/
var Test = function () {
return {a: 'asdasd'};
}
var some = Test();
some instanceof Test; //logs false
/*Style of writing classes*/
/*No: 1 - Prototypal Pattern*/
var Car = function(loc) {
this.loc = loc;
};
Car.prototype.move = function() {
this.loc++;
}
/*No: 2 - Functional Class Pattern*/
var Car = function(loc) {
var obj = Object.create(Car.methods);
obj.loc = loc;
return obj;
};
/*No: 3 - Pseudo-Classical Pattern*/
var Car = function(loc) {
var obj = {loc: loc};
obj.move = function() {
obj.loc++;
}
return obj;
};
var Van = function(loc) {
var obj = Car(loc)
obj.grab = function() {/**/}
return obj;
};
var Cop = function(loc) {
var obj = Car(loc)
obj.call = function() {/**/}
return obj;
};
var amy = Van(2);
amy.grab();
var cop = Cop(3);
cop.call();
/*Pseudoclassical Subclasses*/
/*No: 1*/
var Car = function(loc) {
this.loc = loc;
}
Car.prototype.move = function() {
this.loc++;
}
var zed = new Car(3);
zed.move(); //sets loc = (3 + 1) = 4
/*No: 2 - Building out a Subclass*/
var Car = function(loc) {
this.loc = loc;
}
Car.prototype.move = function () {
this.loc++;
}
var Van = function(loc) {
Car.call(this, loc)
}
Van.prototype = Object.create(Car.prototype);
Van.constructor = Car;
Van.prototype.grab = function() {
/**/
}
var amy = new Van(2);
amy.move()
amy.loc//logs 3
amy.move()
amy.loc//logs 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment