Last active
May 8, 2018 02:46
-
-
Save alvarezmauro/f2abce67b96304450a7dd30b06ef6c64 to your computer and use it in GitHub Desktop.
JS Design patterns - Inheritance - Explicit prototype declaration, Object.create, method factory
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
var Animal = { | |
create(type){ | |
var animal = Object.create(Animal.prototype); | |
animal.type = type; | |
return animal; | |
}, | |
isAnimal(obj, type){ | |
if(!Animal.prototype.isPrototypeOf(obj)){ | |
return false; | |
} | |
return type ? obj.type === type : true; | |
}, | |
prototype: {} | |
}; | |
var Dog = { | |
create(name, breed){ | |
var dog = Object.create(Dog.prototype); | |
Object.assign(dog, Animal.create("dog")); | |
dog.name = name; | |
dog.breed = breed; | |
return dog; | |
}, | |
isDog(obj){ | |
return Animal.isAnimal(obj, "dog"); | |
}, | |
prototype: { | |
bark(){ | |
console.log("ruff, ruff"); | |
}, | |
print(){ | |
console.log("The dog " + this.name + " is a " + this.breed); | |
} | |
} | |
}; | |
Object.setPrototypeOf(Dog.prototype, Animal.prototype); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment