
apply、call、bind是挂载在Function对象上的三个方法,调用这三个方法必须是一个函数。
- 在浏览器里,全局范围内的this指向window
- 在函数内,this永远指向最后调用他的那个对象
- 在构造函数中,this指向new出来的那个对象
- call、apply、bind中的this被强制绑定在指向的那个对象上
- 箭头函数中的this比较特殊,其this指向其父作用域的this
实现一个bind函数
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') {
throw new Error('类型错误')
}
let _this = this
let args = Array.prototype.slice.call(arguments, 1)
return function () {
_this.apply(context, args.concat(arguments))
}
}
实现一个apply函数
Function.prototype.myApply = function (context) {
if (typeof this !== 'function') {
throw new Error('类型错误')
}
let key = Symbol('key')
context[key] = this
let result = context[key](Array.prototype.slice.call(arguments, 1))
delete context[key]
return result
}
实现一个call函数
Function.prototype.myCall = function (context, ...ags) {
if (typeof this !== 'function') {
throw new Error('类型错误')
}
let key = Symbol('key')
context[key] = this
let reslut = context[key](...ags)
delete context[key]
return reslut
}