====== JavaScript プロトタイプチェーン ====== --- //[[http://www.y2sunlight.com/water|y2sunlight]] 2021-05-12// ===== prototypeオブジェクト ===== var Student = function(name) { this.name = name; }; Student.prototype.greeting = function() { console.log(`I am ${this.name}.`); }; // 年齢(age)はオブジェクト毎に保持されるべきなので、prototypeには適さない。 // 但し参照のみの初期値として使用することはできる。 Student.prototype.age = 15; // suzukiはStudentのprototypeの参照を保持する。 var suzuki = new Student('suzuki'); suzuki.greeting(); // 結果:I am suzuki. === プロトタイプを使用するメリット === - メモリ量の節約できる - メンバの追加/変更が即座に反映される \\ ===== プロトタイプチェーン ===== 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プロパティは継承元を返す。 \\ ===== isPrototypeOfメソッド ===== 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のプロトタイプに存在するか否かを返す。 \\