apply
var applyFn = function (name,age) {
console.log(`${name}说:${this.msg},我${age}岁了`)
}
var applyObj = {
msg: '你好'
}
applyFn.apply(applyObj,['Demon',18]) // Demon说:你好,我18岁了
call
var callFn = function (name,age) {
console.log(`${name}说:${this.msg},我${age}岁了`)
}
var callObj = {
msg: '你好'
}
callFn.call(callObj,'Demon',18) // Demon说:你好,我18岁了
bind
var bindFn = function (name,age) {
console.log(`${name}说:${this.msg},我${age}岁了`)
}
var bindObj = {
msg: '你好'
}
const hello = bindFn.bind(bindObj,'Demon',18)
hello('123') // Demon说:你好,我18岁了
通过上面的三个例子可以看出
1.apply继承的第二个参数是一个数组,call、bind 参数是多个
2.bind继承返回的是一个新的函数所以bind不会改变原函数的this指向,call、apply返回的是一个结果
简单实现apply继承
Function.prototype.myApply = function (cxt,argument) {
const fn = Symbol() // 临时属性
cxt[fn] = this // 让对象中的临时属性等于当前this指向的函数
cxt[fn](...argument) // 执行对象中临时属性对应的函数并将参数放入
delete cxt[fn] // 删除该对象中的临时属性
}
简单实现call继承
同apply继承一样,只是参数的形式不同
Function.prototype.myCall = function (cxt,...argument) {
const fn = Symbol() // 临时属性
cxt[fn] = this // 让对象中的临时属性等于当前this指向的函数
cxt[fn](...argument) // 执行对象中临时属性对应的函数并将参数放入
delete cxt[fn] // 删除该对象中的临时属性
}
简单实现bind继承
Function.prototype.myBind = function (cxt,...arguments) {
const that = this
const newFn = function (...newArguments) {
return that.myCall(cxt,...arguments,...newArguments)
}
newFn.prototype = Object.create(that.prototype)
return newFn
}