Water Sunlight

軽量プログラミングの文法 - JavaScript/Python

ユーザ用ツール

サイト用ツール


js:object:chain

文書の過去の版を表示しています。


JavaScript プロトタイプチェーン

y2sunlight 2021-05-12

プロトタイプチェーン

var Animal = function(){};    // Animalクラス
Animal.prototype.cry = function() {
    console.log('woooo');
};

var Dog = function(){};       // Dogクラス
Dog.prototype = new Animal();
Dog.prototype.cry = function() {
    console.log('bowwow');
};

var Rabbit = function(){};  // Rabbitクラス
Rabbit.prototype = new Animal();

var taro = new Dog();
var coco = new Rabbit();

taro.cry();  // 結果:bowwow
coco.cry();  // 結果:woooo

var Animal = function(name){
    this.name = name;
};

Animal.prototype.cry = function() {
    console.log(this.name + " cry: 'woooo'.");
};


var Dog = function(name){
    Animal.call(this, name);
};
Dog.prototype = new Animal();

var taro = new Dog('Taro');
taro.cry();  // Taro cry: 'woooo'.

constructorプロパティとinstanceof

var Animal = function(){};    // Animalクラス
var Dog = function(){};       // Dogクラス
var Flower = function(){};    // Flowerクラス
Dog.prototype = new Animal(); // DogのAnimalの継承

var a = new Dog();    // Dogのインスタンス化
var b = new Flower(); // Flowerのインスタンス化

console.log(a.constructor === Animal);  // 結果:true
console.log(a.constructor === Dog);     // 結果:false
console.log(b.constructor === Animal);  // 結果:false
console.log(b.constructor === Flower);  // 結果:true

console.log(a instanceof Animal);       // 結果:true
console.log(a instanceof Dog);          // 結果:true
console.log(b instanceof Animal);       // 結果:false
console.log(b instanceof Flower);       // 結果:true

constructorプロパティは継承元を返す


constructorプロパティとinstanceof

var Animal = function(){};    // Animalクラス
var Dog = function(){};       // Dogクラス
var Flower = function(){};    // Flowerクラス
Dog.prototype = new Animal(); // DogのAnimalの継承

var a = new Dog();    // Dogのインスタンス化
var b = new Flower(); // Flowerのインスタンス化

console.log(Animal.prototype.isPrototypeOf(a));  // 結果:true
console.log(Animal.prototype.isPrototypeOf(b));  // 結果:false
console.log(Flower.prototype.isPrototypeOf(a));  // 結果:false
console.log(Flower.prototype.isPrototypeOf(b));  // 結果:true

obj.prototype.isPrototypeOf(a)はobjプロトタイプがaのプロトタイプに存在するか否かを返す


js/object/chain.1620779931.txt.gz · 最終更新: 2021/05/12 09:38 by tanaka