从this的隐式绑定入手
我们都知道函数中this的指向只取决于该函数的调用位置,且其有四种绑定形式。即
- 默认绑定
- 隐式绑定
- 显示绑定
- new绑定
而显示绑定是借用了一些方法。如call、apply,bind。但是它们的怎么实现的呢?
答:它们均是基于隐式绑定基础之上的
先来看什么是隐式绑定,看下面代码:
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
};
obj.foo();
全局情况下的默认绑定之所以绑到了全局,是因为函数调用位置在全局的上下文中,而这里的调用位置拿到的上下文是obj的。
call,apply的实现均是基于隐式绑定,知晓了思路实现便非常简单了
实现:
Function.prototype.myCall = function(context = window) {
context.fn = this;
let res = context.fn(...([...arguments].slice(1)));
delete context.fn;
return res;
}
Function.prototype.myApply = function(context = window, arr) {
context.fn = this;
let res;
if (!arr) {
res = context.fn();
} else {
res = context.fn(...arr);
}
delete context.fn;
return res;
}
console.log(...[1, 2, 3]);
Function.prototype.myBind = function(contextcontext = window) {
let that = this;
let args = [...arguments].slice(1);
return function() {
return that.apply(context, args);
}
}
function a(b, c) {
console.log(this.d,b,c);
}
let e = {
d: 1
}
a.myApply(e,[2,3])
a.myCall(e,2,3)
a.myBind(e,2,3)()