Last active
February 26, 2021 00:47
-
-
Save JaysonChiang/d5d7355e9638a1937cfbdf9f4de00bcc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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