一、类的声明
function Animal(){
this.name="name"
}
//es6
class Animal2{
constructor(){
this.name="name"
}
}
实例化一个类
new Animal()
二、JS有哪些手段可以实现继承?
es5
1.forEach 因为对象属性是伪数组
function Parent(name){
this.name=name
}
function Child(name){
var parent=new Parent();
for(var i in parent) {
Child.prototype[i]=parent[i]
}
}
2.借助构造函数来实现类的继承(无法继承原型对象上的属性)。
function Parent1() {
this.name="parent1"
}
function Child1(){
Parent1.call(this)
this.type="child1"
}
用到函数的两个方法call和apply
Parent1.call(this)
1、执行了Parent1()方法
2、改变了this指向 (child1对象)
缺点: 部分继承,只能继承父类构造函数中的属性和方法,原型对象上的属性和方法无法继承。
function Parent1() {
this.name="parent1"
}
Parent1.prototype.say=function(){};
function Child1(){
Parent1.call(this)
this.type="child1"
}
3.借助原型链来实现继承
function Parent2(){
this.name="parent2"
}
function Child2(){
this.type="child2"
}
Child2.prototype=new Parent2();
缺点 :子构造函数new出来的对象的原型是一样的,导致修改从原型对象继承而来的属性或者方法在一个子对象中被修改时会影响到其他子对象,这是我们不需要的。
function Parent2(){
this.name="parent2"
this.arr=[1,2,3]
}
function Child2(){
this.type="child2"
}
Child2.prototype=new Parent2();
var child1=new Child2();
var child2=new Child2()
child1.arr.push(4);
console.log(child1.arr)
console.log(child2.arr)
4.构造函数与原型链组合实现继承
function Parent3(){
this.name="parent3"
this.arr=[1,2,3]
}
function Child3(){
Parent3.call(this)
this.type="child3"
}
Child3.prototype=new Parent3() //缺点 父类的构造函数运行了两次 优化如下
Child3.prototype=Parent3.prototype
var child1=new Child3()
var child2=new Child3()
child1.arr.push(4)
console.log(child1.arr)
console.log(child2.arr)
优化后出现问题
child1 instanceof Child3 为true
child1 instanceof Parent4 为true
function Parent3(){
this.name="parent3"
this.arr=[1,2,3]
}
function Child3(){
Parent3.call(this)
this.type="child3"
}
Child3.prototype=new Parent3() //缺点 父类的构造函数运行了两次 优化如下
Child3.prototype=Parent3.prototype
var child1=new Child3()
var child2=new Child3()
child1.arr.push(4)
console.log(child1.arr)
console.log(child2.arr)
console.log( child1 instanceof Child3)
console.log( child1 instanceof Child3)
console.log(child1.constructor)
最优方案
function Parent3(){
this.name="parent3"
this.arr=[1,2,3]
}
function Child3(){
Parent3.call(this)
this.type="child3"
}
Child3.prototype=new Parent3() //缺点 父类的构造函数运行了两次 优化如下
Child3.prototype= Object.create(Parent3.prototype)
Child3.prototype.constructor=Child3
var child1=new Child3()
var child2=new Child3()
child1.arr.push(4)
console.log(child1.arr)
console.log(child2.arr)
console.log(child1 instanceof Child3)
console.log(child1 instanceof Child3)
console.log(child1.constructor)