原型继承写法

94 阅读1分钟

组合寄生继承

function Animal(name, age) {
   this.name = name;
   this.age = age;
}

Animal.prototype.getName = function() {
 	return this.name;
}

Animal.prototype.getAge = function() {
 	return this.name;
}

function Pig(name, age) {
 	Animal.call(this, name, age); //相当于调用父级的构造函数 super()
}

Pig.prototype = Object.create(Animal.prototype); //将Pig的原型创建为Animal的原型,实现原型链继承

Pig.prototype.constructor = Pig;

Object.defineProperty(Pig.prototype, 'constructor', {
 	enumerable: false
})

let pig1 = new Pig('小香猪', '1');