ES5形式
function fun() {
this.name = 'fun',
this.arr = [1,2,3]
}
fun.prototype.myLog = function() {
console.log(this.arr);
}
function cFun () {
fun.call(this) //call调用父函数 继承父函数的属性
this.type = 'child'
}
cFun.prototype = fun.prototype // 构造函数的原型对象指向要继承的父函数的原型对象
cFun.prototype.constructor = cFun
var c1 = new cFun()
console.log(c1);
c1.myLog()
console.log(c1 instanceof cFun); // true
console.log(f1 instanceof cFun); // true
执行结果如图:
image.png
缺点:因为父函数和子函数都是同一个对象,导致父函数和子函数的实例对象,在执行instanceof时,都为true 无法区分。
用Object.creacte(fun.prototype)创建中间对象的形式可以解决这个问题
ES6形式
class Teacher {
constructor(name) {
this.name = name
this.age = 30
}
sayHi() {
console.log(`hello everyone,我叫${this.name}`);
}
}
class Student extends Teacher {
constructor(name) {
super(name)
this.name = name
}
sayHello() {
console.log(`大家好,我叫${this.name}`);
}
}
const stu1 = new Student('张三')
console.log(stu1);
stu1.sayHello()
stu1.sayHi()
结果如下:
image.png