手写bind函数
核心代码演示:
初始化:
function fn1(a,b,c) {
console.log('this',this);
console.log(a,b,c);
return 'this is fn1'
}
//bind可以传递多个参数,第一个参数是要绑定this,第二个参数a/b/c,都要传进去
const fn2 = fn1.bind({x:100}, 10, 20, 30)
const res = fn2();
console.log(res);
效果:
Array.prototype.shift():把数组的第一项永远的挖出来,只剩下后面的数组
手写bind函数:
核心代码演示:
//类似jquery 插件机制
//模拟bind
/**
* 首先,bind这个函数需要接收很多个参数,我们不知道接收多少个,第一个参数是{}this,后面不知道传递多少个参数
* 所以这里没法去接收参数,怎么办呢?
*/
Function.prototype.bind1 = function () {
//将参数拆解为数组,参数可以通过arguments来获取,argument可以获取一个函数所有的参数,不管多少个,argument是列表形式,不是数组,所以把它变为数组
//Array.prototype.splice.call 把列表变为数组
const args = Array.prototype.splice.call(arguments)
//获取this(数组第一项)
const t = args.shift();
//fn1.bind(...)中的fn1
const self = this
//返回一个函数
return function () {
//执行
//apply(第一个参数是this,第二个参数是数组)
return self.apply(t, args);
}
}
function fn1(a, b, c) {
console.log('this', this);
console.log(a, b, c);
return 'this is fn1'
}
//bind可以传递多个参数,第一个参数是要绑定this,第二个参数a/b/c,都要传进去
const fn2 = fn1.bind1({ x: 100 }, 10, 20, 30)
const res = fn2();
console.log(res);
效果: