不支持new
Function.prototype.fakeBind = function (obj, ...args) {return (...rest) => this.call(obj, ...args, ...rest);};function f(arg) {console.log(this.a, arg);}// output: 3, 4f.bind({ a: 3 })(4);// output: 3, 4f.fakeBind({ a: 3 })(4);
if (!Function.prototype.bind) {Function.prototype.bind = function(o /*, args */) {var self = this, boundArgs = arguments;//如果不提前保存this,在执行函数时内部this会指向windowreturn function () {var i, args = [];for (i = 1; i < boundArgs.length; i++) {//第0位是this,所以得从第一位开始裁剪args.push(boundArgs[i])}for (i = 0; i < arguments.length; i++) {args.push(arguments[i])}return self.apply(o, args)}}}
Function.prototype.myBind=function(obj){let arg=Array.from(arguments);//Array.prototype.slice.call(arguments, 1);arg.shift();let _this=this;return function(){let arg1=arguments;return _this.call(obj,...arg,...arg1)}}
简略地支持new
Function.prototype.myBind=function(obj){// console.log(this);let arg=Array.from(arguments);arg.shift();let _this=this;let res= function(){let arg1=arguments;// console.log(this);_this.call(this.constructor === _this ? this : obj,...arg,...arg1)}res.prototype = _this.prototype;return res;}function f(arg) {this.b=123console.log(this.a, arg);}// output: 3, 4// f.bind({ a: 3 })(4);// output: 3, 4let temp=f.myBind({ a: 3 },4);let t=new temp();console.log(t.b);
