先说说,this 就相当于我们人的父母,谁生下我,谁就是我的父母。对应到我们的函数中的this就是谁调用了我,我就指向谁。但是!我们人不仅有亲生父母,也可能因为家庭的缘故会有养父养母。在我们函数中也是一样的,我可能不想让我的this绑定到我的调用者身上,所以这时我们就需要其他的一些处理手段,也就是本文的主角call、apply、bind
基本使用方法:
var obj = { name: "张三" };
function fn(a, b) {
console.log(a, b);
console.log(this.name);
}
fn.call(obj, 'call', 1);
fn.apply(obj, ['apply', 1]);
fn.bind(obj)('bind', 1);
fn.bind(obj, 'bind')(2);
手写试试?
1、call
Function.prototype.call_ = function (context, ...args) {
context = (context === null || context === undefined) ? window : context;
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
};
2、apply
Function.prototype.apply_ = function (content, arr) {
context = (context === null || context === undefined) ? window : context;
context.fn = this;
const result = context.fn(...arr);
delete context.fn;
return result;
};
3、bind
Function.prototype.bind_ = function (context, ...args1) {
context = (context === null || context === undefined) ? window : context;
let _this = this;
return function (...args2) {
context.fn = _this;
const result = context.fn(...[...args1, ...args2]);
delete context.fn;
return result;
};
};