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 () {
// args.concat(arguments) 这两个顺序不能变 arguments为类数组没有concat方法
_this.apply(context, args.concat(arguments))
}
}
复制代码
实现一个apply函数
// 实现原理 this永远指向最后调用他的那对象
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
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END