练练看
题目:
使用 call 实现 bind
分析:
call, bind, apply都是用作绑定第一个参数为执行作用域
call(this, …) 会使方法自动执行
apply(this, []) 绑定执行作用域
bind(this, …) 创建一个新的函数,在bind()被调用时,新函数的this被bind的第一个参数指定,其余的参数将作为新函数的参数供调用时使用
第一直觉:咩有第一直觉了…
实现:
Function.prototype.myBind = function(context) {
let self = this;
// arguments是类数组需要转换成真正的数组使用
// 把第一个参数去掉,之后的参数作为函数的参数传递
let args = Array.prototype.slice.call(arguments, 1);
let fn = function() {
// 模拟执行bind返回函数时的传参
let bindArgs = Array.prototype.slice(arguments);
let that = this instanceof self ? this : context;
self.apply(that, args.concat(bindArgs));
}
// 继承所绑定函数的原型
fn.prototype = this.prototype;
return fn;
}
测试:
var obj={
name: "z1",
}
var name= "zzy";
function foo(tel) {
console.log(this.name);
console.log(tel);
}
var bindFoo = foo.myBind(obj, "110");
bindFoo()
// z1
// 110
// 作为构造函数使用时,this指向该构造函数本身
var newbindFoo = new bindFoo();
// undefinde
// 110