不支持new

    1. Function.prototype.fakeBind = function (obj, ...args) {
    2. return (...rest) => this.call(obj, ...args, ...rest);
    3. };
    4. function f(arg) {
    5. console.log(this.a, arg);
    6. }
    7. // output: 3, 4
    8. f.bind({ a: 3 })(4);
    9. // output: 3, 4
    10. f.fakeBind({ a: 3 })(4);
    1. if (!Function.prototype.bind) {
    2. Function.prototype.bind = function(o /*, args */) {
    3. var self = this, boundArgs = arguments;
    4. //如果不提前保存this,在执行函数时内部this会指向window
    5. return function () {
    6. var i, args = [];
    7. for (i = 1; i < boundArgs.length; i++) {
    8. //第0位是this,所以得从第一位开始裁剪
    9. args.push(boundArgs[i])
    10. }
    11. for (i = 0; i < arguments.length; i++) {
    12. args.push(arguments[i])
    13. }
    14. return self.apply(o, args)
    15. }
    16. }
    17. }
    1. Function.prototype.myBind=function(obj){
    2. let arg=Array.from(arguments);
    3. //Array.prototype.slice.call(arguments, 1);
    4. arg.shift();
    5. let _this=this;
    6. return function(){
    7. let arg1=arguments;
    8. return _this.call(obj,...arg,...arg1)
    9. }
    10. }

    简略地支持new

    1. Function.prototype.myBind=function(obj){
    2. // console.log(this);
    3. let arg=Array.from(arguments);
    4. arg.shift();
    5. let _this=this;
    6. let res= function(){
    7. let arg1=arguments;
    8. // console.log(this);
    9. _this.call(this.constructor === _this ? this : obj,...arg,...arg1)
    10. }
    11. res.prototype = _this.prototype;
    12. return res;
    13. }
    14. function f(arg) {
    15. this.b=123
    16. console.log(this.a, arg);
    17. }
    18. // output: 3, 4
    19. // f.bind({ a: 3 })(4);
    20. // output: 3, 4
    21. let temp=f.myBind({ a: 3 },4);
    22. let t=new temp();
    23. console.log(t.b);