手写bind的问题
来源:4-4 问题解答
Valar丶Morghulis
2020-04-23
Function.prototype.bind1=function(){
const self = this;
const args = Array.prototype.slice.call(arguments);
const context = args.shift();
return function(){
return self.apply(context,args);
}
}
function fn1(a,b,c){
console.log(this);
console.log(a,b,c);
return '112321'
}
const f2 =fn1.bind1({name:'张三'},12,42)
console.log(f2(4,1));
这里有没有可能f2也会传入参数呢?如果有可能这块地方该如何写?
写回答
3回答
-
h4ck3r
2020-06-10
//模拟 bind Function.prototype._bind = function (...args) { const target = args[0] const self = this const selfArgs = args.filter((_value, index) => index !== 0) return (...targetArgs) => { return self.apply(target, [...selfArgs, ...targetArgs]) } } function fn1(a, b, c) { console.log('this:', this) console.log(a, b, c) return 'this is fn1' } fn2 = fn1._bind({ x: 100 }, 10, 20) const res = fn2(30) //this: { x: 100 } //10 20 30 console.log('res:', res) //res: this is fn1 console.log(fn1 === fn2) //false00 -
玥玥颜
2020-05-26
function fn1(a,b){ console.log(this,a,b) return 'this is fn1' } Function.prototype.bind1=function(){ // 获取this var args=Array.prototype.slice.call(arguments) var self=this var target=args.shift() //返回一个函数 return function(){ var args2=args.concat(Array.from(arguments)) return self.apply(target,args2) } } var fn2=fn1.bind1({x:100},23,445) var res=fn2(3,2)这样可以,bind1返回来的函数就是fn2,所以可以直接在返回的函数里面使用arguments
00 -
双越
2020-04-24
可以在这个函数中获取 arguments ,然后再拼接到 apply 后面。可以先自己试着写一写,有问题再来回复。
return function () { return self.apply(t, args) }00
相似问题