在js中,es6之前是没有类的,类的概念是从es6开始提出来的. 所以JS中的继承应该理解为原型链继承.
js的继承就是由原型链作为实现继承的主要方法. 每一个构造函数都拥有一个原型对象,基本思想就是利用原型让一个引用类型继承另一个引用类型的属性和方法.或者说,js中的一个子类别继承自父类别,便使得子类具有了父类的各种属性和方法.
JS继承的方式
分别说一下经典的prototype 继承,和 ES6的class继承.
1. 原型链继承
基本原理就是将一个构造函数的原型对象赋值给另一个的实例 function Parent(name){
this.name=name
this.genter='男'
}
//声明一个原型链上面的属性
Parent.prototype.sayname=function(){
console.log('你的身份是'+this.name)
}
function Child(name){
this.name=name
}
Child.prototype=new Parent('爸爸')//这里就是继承了Parent的属性方法
var child=new Child('儿子')
child.sayname() //'你的身份是儿子'
复制代码
2. 类式继承
function Parent(name){
this.name=name
}
Parent.prototype.sayname=function(){
console.log('你的身份是'+this.name)
}
function Child(name){
Parent.call(this,name)
}
Child.prototype.__proto__=Parent.prototype //这一句就实现了继承,Child拥有了sayname方法
var child=new Child('宝宝')
console.log(child)
复制代码
缺点:会继承父类的一些不必要的属性,比如说genter属性,我们不需要知道.
解决方法:
f=function(){}
f.prototype=Parent.prototype
Child.prototype=new f()
复制代码
es6 的写法
class Parent {
constructor(name){
this.name=name
}
sayname(){
console.log('你的身份是'+this.name)
}
}
class Child extends Parent{
constructor(name){
super(name)
}
get age(){
return '21'
}
}
var child =new Child('宝宝')
child.sayname()//你的身份是宝宝
复制代码
缺点:不能在child.prototype上定义非函数的属性,
比如child.age 用传统ES5写法可以写为age:"21"
在class 中只能用函数return出来.