继承的目标就是为了让一个援用类型能够应用另一个援用类型的属性和办法
首先写一个父类
//constructor 构造函数
function Animal(name) {
this.name = name
}
//增加原型办法
Animal.prototype.eat = function(food) {
console.log(this.name + "正在吃" + this.food)
}
var cat = new Animal('cat')
console.log(cat)
截图中能够看到实例cat自带的构造方法属性和原型办法
1.原型链继承
//constructor 构造函数
function Animal(name) {
this.name = name
}
//增加原型办法
Animal.prototype.eat = function(food) {
console.log(this.name + "正在吃" + this.food)
}
//子类的构造函数
function Cat() {}
Cat.prototype = new Animal(); //重点代码
Cat.prototype.name = 'cat';
var cat = new Cat()
console.log(cat)
特点:
1.cat是Cat()的实例,也是Animal()的实例
2.Cat()和Animal()新增属性和办法,cat都能拜访到
毛病:
1.想为Cat()新增属性和办法,必须要在new Animal()这样的语句之后执行
2.来自原型对象的所有属性被所有实例共享,造成非必要内存空间
3.创立cat实例时,无奈向父类构造函数传参
2.结构继承
发表回复