Object.create:
如下圖的Dog02利用Object.create來獲取Dog01的屬性,但是不會顯示出來。
var Dog01 = {
name: 'TOM',
size: 'big',
color: 'yellow'
};
var Dog02 = Object.create(Dog01);
console.log(Dog02);
賦予Dog02新的屬性name。
var Dog02 = Object.create(Dog01);
console.log(Dog02);
Dog02.name = 'Mary';
多層繼承:
function Animal(腿) { //創一個父層Animal的屬性
this.move = '會動';
this.breath = '會呼吸';
this.腿 = 腿 + '條腿';
};
Animal.prototype.run = function () { //創一個父層Animal的method
console.log('路上或海上');
};
function dog(name, color) { //創一個子層dog的屬性
Animal.call(this, 4); //自訂子層狗的參數,運用到來自父層animal的屬性。
this.name = name;
this.color = color;
};
dog.prototype.eat = function () { //創一個次層dog的method
console.log('乖乖吃');
};
連接父層Animal與子層dog:
在中間利用Object.create,並利用().prototype.constructor來重建dog的constructor。
dog.prototype = Object.create(Animal.prototype);
dog.prototype.constructor = dog;
function Animal(腿) {
this.move = '會動';
this.breath = '會呼吸';
this.腿 = 腿 + '條腿';
};
Animal.prototype.run = function () {
console.log('路上或海上');
};
dog.prototype = Object.create(Animal.prototype);
dog.prototype.constructor = dog;
function dog(name, color) {
Animal.call(this, 4);
this.name = name;
this.color = color;
};
dog.prototype.eat = function () {
console.log('乖乖吃');
};
var dog01 = new dog('TOM', 'RED'); //利用建構子自訂一隻實體狗
console.log(dog01);
dog01.eat();
dog01.run();
練習:創造父層animal,及2個子層動物且擁有不同的methods。
animal.prototype.run = function (腿) {
if (腿 > 0) {
console.log(this.name + '是路上走');
}
else {
console.log(this.name + '是海裡游');
};
};
fish.prototype = Object.create(animal.prototype);
fish.prototype.constructor = fish;
function fish(name, color, size) {
animal.call(this, 0);
this.name = name;
this.color = color;
this.size = size;
};
fish.prototype.eat = function () {
console.log(this.name + ' 乖乖吃');
};
cat.prototype = Object.create(animal.prototype);
cat.prototype.constructor = cat;
function cat(name, color, size) {
animal.call(this, 4);
this.name = name;
this.color = color;
this.size = size;
};
cat.prototype.eat = function () {
console.log(this.name + ' 喵喵吃');
};
var cat01 = new cat('kitty', 'brown', 'small');
var fish01 = new fish('Shark', 'RED', 'big');
console.log(cat01);
cat01.eat();
cat01.run(4);
console.log(fish01);
fish01.eat();
fish01.run(0);