回忆录
记得有一次面试,面试官问我,js怎么实现继承?
我并没有思考,直接脱口而出,可以使用call()和apply()可以实现继承,他笑了笑
就没有然后了....
后来他问你还有什么要问的吗?我说我想知道js怎么实现继承,希望能得到你的指点
然后他说原型链,你的js基础还很差...
所以想再学习一遍,加深印象,希望能得到各路前辈的指点
前言
文档中是这样介绍的,call()和apply()方法作用类似,都是改变函数内部this的指向;只有一个区别就是call()方法接受的是若干个参数列表,而apply()方法接受的是若干个参数的数组
call()
fun.call(thisArg, arg1, arg2, arg3, ...)
apply()
fun.apply(thisArg, [arg1, arg2, arg3, ...])
用thisArg代替了fun调用fun内部的操作,我的理解是类似于Java的继承(它们并非实现继承而来的);如thisArg为null和undefinden时,在非严格模式下会自动指向全局对象(Window对象)
示例一
function Person(name, age) {
this.name = name
this.age = age
//当new Student()时,这个this指向的就是Student对象
//当new Person()时,this指向的就是Person对象
console.log(this)
//new Student()时 输出的是 : 张三 25岁
//new Person()时 输出的是 :李四 23岁
console.log(this.name + " " + this.age + "岁")
}
function Student(name, age) {
//这里会执行Person内部的操作
Person.call(this, name, age)
//Person.apply(this, [name, age]) call和apply作用类似,区别在于传参
//这个this指向的是当前对象
console.log(this)
}
var stu1 = new Student("张三", 25)
console.log(stu1) //Student对象
var stu2 = new Person("李四", 23)
console.log(stu2) //Person对象
示例二
function Person(name, age) {
this.name = name
this.age = age
//这个this指向的是全局对象Window
console.log(this)
console.log(this.name + " " + this.age + "岁")
}
function Student(name, age) {
Person.call(null,name, age)
//Person.apply(this, [name, age]) call和apply作用类似,区别在于传参
//这个this指向的是Student
console.log(this)
}
var stu = new Student("张三", 18)
console.log(stu)