关于前端:原型链及其继承

继承的目标就是为了让一个援用类型能够应用另一个援用类型的属性和办法

首先写一个父类

//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.结构继承

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理