— y2sunlight 2021-05-12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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. |
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 |
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'. |
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プロパティは継承元を返す。
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のプロトタイプに存在するか否かを返す。