Water Sunlight

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

ユーザ用ツール

サイト用ツール


js:object:chain

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


JavaScript プロトタイプチェーン

y2sunlight 2021-05-12

プロトタイプチェーン

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

Example
1
2
3
4
5
6
7
8
9
10
11
12
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.1620779956.txt.gz · 最終更新: 2021/05/12 09:39 by tanaka