Skip to content

Instantly share code, notes, and snippets.

@JaysonChiang
Last active February 26, 2021 00:47
Show Gist options
  • Save JaysonChiang/d5d7355e9638a1937cfbdf9f4de00bcc to your computer and use it in GitHub Desktop.
Save JaysonChiang/d5d7355e9638a1937cfbdf9f4de00bcc to your computer and use it in GitHub Desktop.
// public method
function Bike() {}
Bike.prototype.ride = function () {
return "I ride " + this.brand;
};
// static method
function BikeMaker() {}
BikeMaker.factory = function (brandname) {
if (typeof BikeMaker[brandname] !== "function") {
throw {
name: "Error",
message: brandname + " does not exist",
};
}
if (typeof BikeMaker[brandname].prototype !== "function") {
BikeMaker[brandname].prototype = new Bike();
}
return new BikeMaker[brandname]();
};
BikeMaker.giant = function () {
this.brand = "Giant";
};
BikeMaker.merida = function () {
this.brand = "Merida";
};
var mybike = BikeMaker.factory("giant");
var yourbike = BikeMaker.factory("merida");
console.log(mybike.ride()); // This bike is Giant
console.log(yourbike.ride()); // This bike is Merida
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment