JavaScript継承
出展http://postd.cc/javascript-inheritance-patterns/
by s_hiroshi
JavaScript
/*
* http://postd.cc/javascript-inheritance-patterns/
*
* メソッド3:明示的なプロトタイプの宣言、Object.create、ファクトリメソッド
* このメソッドでは、classシンタックスの後に、プロトタイプ継承を実際に表示することができます。また、newキーワードを省くことが可能です。
*/
var Animal = {
create(type){
// Object.create
// https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/create
var animal = Object.create(Animal.prototype);
animal.type = type;
return animal;
},
isAnimal(obj, type){
// Object.prototype.isPrototypeOf
// https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf
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
// https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
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);
/*
このシンタックスは大変優れていて、プロトタイプがとても明示的に定義されます。どちらがプロトタイプのメンバで、どちらがオブジェクトのメンバかがはっきりと分かります。また、Object.createの優れている点は、ある特定のプロトタイプからオブジェクトを生成できるところです。どちらの場合も、.isPrototypeOfによるチェックは可能です。使い方は異なりますが、大きな違いではありません。
*/
var sparkie = Dog.create("Sparkie", "Border Collie");
console.log(sparkie.name); // "Sparkie"
console.log(sparkie.breed); // "Border Collie"
sparkie.bark(); // console: "ruff, ruff"
sparkie.print(); // console: "The dog Sparkie is a Border Collie"
console.log(sparkie.type);
Dog.isDog(sparkie); // true