组合继承在结合原型链继承和构造器继承,结合了两者的优点,用原型链继承方法,将公用的方法放在构造函数下面的原型对象上;用构造器继承属性,避免了引用类型的属性被所有实例共享;
//组合继承
function Father(name,age){
this.name=name
this.age=age;
this.say=function(){
console.log(this.name)
}
}
Father.prototype.walk=function(){//在对象原型对象上设置方法
console.log(this.age)
}
function Son(sex){
//继承属性 原型属性
Father.call(this,name)
this.sex=sex
}
//继承方法
Son.prototype=new Father()//原型链继承,接下来通过对Son进行new实例化后的所有对象上都有一个原型属性
Son.prototype.constructor=Son
var son1=new Son()
console.log(Son.prototype.hasOwnProperty("say"))//true
console.log(Son.prototype.hasOwnProperty("walk"))//false
console.log(Son.prototype.hasOwnProperty("age"))//true在构造器的原型上也有age
console.log(son1.hasOwnProperty("age"))//true 在构建的实例对象上也有
console.log(Son.hasOwnProperty("age"))//false 但是在Son上面没有只有在进行son实例化时才有
学习的一个小总结:如果原型这方面不了解哪个属性的位置不确定的话,最好自己可以用编译器上跑一下