function Father (name, age) {
// this指向父构造函数的对象实例
this.name = name
this.age = age
this.money = function () {
console.log('挣了1000元')
}
}
function Son (name, age) {
// this指向子构造函数的对象实例
Father.call(this, name, age)
this.exam = function () {
console('考试') //新增方法
}
}
var son = new Son('小明', 12)
console.log(son.name) //小明
console.log(son.age) //12
son.money() //挣了1000元
方法二:通过原型链的方法
function Father () {
}
Father.prototype.hello = 'hello'
Father.prototype.money = function () {
console.log('挣了1000元')
}
function Son () {
}
Son.prototype = new Father() //将Father中所有通过prototype添加的属性和方法都追加到Son上面,进而实现继承
var son = new Son()
console.log(son.hello) //hello
son.money() //挣了1000元
方法三:通过 apply()方法
function Father (name, age) {
this.name = name
this.money = function () {
console.log('挣了1000元')
}
}
function Son (name,age) {
Father.call(this, [name, age])
this.exam = function () {
console('考试') //新增方法
}
}
var son = new Son('小明',12)
son.money() //挣了1000元
方法四:混合原型链和 call()方法
function Father (name, age) {
this.name = name
this.age = age
}
Father.prototype.money = function () {
console.log('挣了1000元')
}
function Son (name, age) {
Father.call(this, name, age)
}
Son.prototype = new Father()
var son = new Son('小明', 12)
console.log(son.name) //小明
son.money() //挣了1000元
ES6中的继承
class Father {
constructor (x, y) {
this.x = x
this.y = y
}
sum () {
console.log(this.x + this.y)
}
}
class Son extends Father {
constructor (x, y) {
super(x, y)
this.x = x
this.y = y
}
subtract () {
console.log(this.x - this.y) //新增方法
}
}
var son = new Son(3,4)
son.sum() //7
son.subtract() //-1