原型链继承
假如有两个类型,一个是父类型,一个是子类型
//父类型
function Supper (){
this.father = "father"
}
Supper.prototype.showSupperProp = function(){
console.log(this.father)
}//往父类型的原型对象上添加一个showSupperProp方法
//子类型
function Sub(){
this.son = "son"
}
var sub = new Sub()
现在要通过sub.showSupperProp()访问这个函数,应该怎么做?
首先要知道showSupperProp()是父类型原型对象上的方法
sub能够访问的方法只能从自己的原型链上找
所以就需要将子类型的原型作为父类型的一个实例对象
所以需要加上
Sub.prototype = new Supper()
Sub.prototype.constructor = Sub
借用构造函数实现类似继承
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name){
this.name = name
}
function Student(name, age, price) {
Person.call(this, name, age)
this.price = price
}
var a = new Student("Zlearn", 20, 1400)
Person.call(this, name, age)相当于
this.Person(name,age)相当于
this.name = name
this.age = age放到Student里面
组合实现继承
借用构造函数得到属性
用原型链继承得到方法
function Student(name, age, price) {
Person.call(this, name, age)
this.price = price
}
Sub.prototype = new Supper()
Sub.prototype.constructor = Sub
var a = new Student("Zlearn", 20, 1400)
a.setName()//可用
a.name//可用