一、手写bind函数
- bind的作用
调用func.bind(obj)的作用是返回一个新函数,并且这个新函数的作用域,即其this指向obj。举个例子:
function func1(){
console.log(this) //在浏览器控制台中输出Windows
}
var obj = {a:1}
var func2 = func1.bind(obj)
func2() //此时浏览器控制台输出obj,bind函数返回了新函数,并且这个函数的上下文是obj。
- 实现
Function.prototype._bind = function(){
//缓存当前this
let _this = this
//缓存当前参数对象
let _arguments = arguments
//将其转换为数组
_arguments = Array.prototype.slice.call(_arguments)
//获取第一个参数,即绑定的目标对象
let target = Array.prototype.shift.call(_arguments)
//定义一个新函数
let fn = function(){
//函数有两种使用方式,一种是普通调用,另一种是作为构造函数调用,即通过new关键字调用,所以这里需要做一个区分,以免new出来的对象的构造函数指向不对。
let ctx = this instanceof fn ? fn : target
_this.apply(ctx, _arguments.concat(Array.prototype.slice.call(arguments)))
}
//将函数的原型指向被绑定函数的原型
fn.prototype = _this.prototype
//返回该函数
return fn
}