前端面试之手写Function.prototype.bind()

215 阅读1分钟

Function.prototype.bind() bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用

const obj = {
	name: 'cat',
	getName: function(){
		return this.name;
	}
}

console.log(obj.getName());//此时this指向obj
// 结果为cat

fn = obj.getName;
console.log(fn());//此时的this是window
// 结果不存在

fn = obj.getName.bind(obj);//绑定作用域到obj
console.log(fn());
// 结果为cat

bind函数参数 thisArg 调用绑定函数时作为 this 参数传递给目标函数的值。 如果使用new运算符构造绑定函数,则忽略该值。当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind 函数的参数列表为空,或者thisArg是null或undefined,执行作用域的 this 将被视为新函数的 thisArg。 arg1, arg2, ... 当目标函数被调用时,被预置入绑定函数的参数列表中的参数。

那么如何实现一个bind函数呢?

Function.prototype.bindFn = function (obj, arg) {
  var args = Array.prototype.slice.call(arguments, 1);
  var context = this;
  return function () {
    var newArgs = args.concat(Array.prototype.slice.call(arguments));
    return context.apply(obj, newArgs)
  }
}

fn = obj.getName.bindFn(obj);//绑定作用域到obj
console.log(fn());
// 结果为cat