继承
2019-10-27 本文已影响0人
真是个非常帅气的昵称呢
prototype:被实例的__proto__指向,属于被动
__proto__:指向构造函数的prototype,属于主动
原型链式继承
优点:父类新增原型属性和方法,子类都能访问
缺点:无法实现多继承;创建子类实例,无法向父类传参;
来自原型对象的属性被所有子类实例共享;修改一个会影响另一个
如果要为子类新增属性和方法,必须放在new Animal()之后
function Animal() {
this.species="动物"
}
function Dog(name,food) {
this.name=name;
this.food=food;
}
Dog.prototype=new Animal()
Dog.prototype.constructor=Dog
var dog1=new Dog('大毛','骨头')
console.log(new Animal().constructor)
console.log(dog1.constructor==Dog)
console.log(dog1.constructor==Dog.prototype.constructor)

function Animal() {}
Animal.prototype.species="动物"
function Dog(name,food) {
this.name=name;
this.food=food;
}
Dog.prototype=Animal.prototype
Dog.prototype.constructor=Dog
var dog1=new Dog('大毛','骨头')
console.log(new Animal().constructor)
console.log(Animal.prototype.constructor)

构造函数继承
优点:解决了子类共享父类引用属性的问题,创建了子类实例,可以向父类传递参数;多继承
缺点:不能访问父类原型方法;实例是子类的实例,不是父类的实例;有多个父函数副本,影响性能
function Animal(name){
this.name=name
this.sleep=function(){
console.log(this.name+'is sleeping ')
}
}
Animal.prototype.eat=function(food){
console.log(this.name+'is eating '+food)
}
function Dog(name,age,color){
Animal.call(this,name)
this.age=age
this.color=color
}
var d1=new Dog('damao',12,'black')