简介
上一篇, 我们介绍了JavaScript鄙视题 - 重写forEach, 我们继续介绍如何手写一个bind方法.
方法介绍
bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被bind的第一个参数指定,其余的参数将作为新函数的参数供调用时使用.
举个例子:
const say = function(message) {
return `${this.name} ${message}`
};
const jack = {name: 'jack'};
const joe = {name: 'joe'};
const jackSay = say.bind(jack);
const joeSay = say.bind(joe);
console.log(jackSay(', I am jack'));
console.log(joeSay(', I am joe'));
// output
// jack, I am jack
// joe, I am joe
通俗一点的讲, 就是改变执行函数this的指向.
重写bind方法.
Function.prototype.bind = function(obj, ...rest){
const fn = this;
return function(...args){
return fn.call(obj, rest.concat(args));
}
};
看起来是否非常的简单.