使用call和原型链实现完整继承
● 要创建中国人、美国人,他们都有共同的属性和方法
○共同的属性:有名字、有年龄
○共同的方法:有吃饭、跑步等行为
● 所以可以抽取一个父对象,包含名字、年龄、吃饭、跑步的行为,让他们继承即可
● 代码如下:
// 人类
function Person(name, age) {
// 只有当name有值并且age也有值时才加
if (name && age) {
this.name = name
this.age = age
}
}
Person.prototype.eat = function () {
console.log('吃啊吃')
}
Person.prototype.run = function () {
console.log('跑啊跑')
}
// 中国人
function Chinese(name, age) {
// 光这么调用还不够
// 因为直接调用函数,函数里的this是window
// 我需要把它里面的this,改成我当前的this
Person.call(this, name, age)
}
// 为了继承,要让中国人的原型对象只想到Person的实例对象
Chinese.prototype = new Person()
Chinese.prototype.constructor = Chinese
// 一定要写在原型链的继承后面
Chinese.prototype.spring = function () {
console.log('过春节')
}
// 美国人
function American(name, age) {
// 属性继承
Person.call(this, name, age)
}
American.prototype = new Person()
American.prototype.constructor = American
// 创建一个中国人对象
let lilei = new Chinese('李雷', 16)
console.log(lilei)
lilei.eat()
lilei.run()
lilei.spring()
// 创建一个美国人
let jim = new American('Jim Green', 16)
console.log(jim)
jim.eat()
jim.run()