Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Q031】js 中如何实现 bind #32

Open
shfshanyue opened this issue Nov 15, 2019 · 6 comments
Open

【Q031】js 中如何实现 bind #32

shfshanyue opened this issue Nov 15, 2019 · 6 comments

Comments

@shfshanyue
Copy link
Owner

shfshanyue commented Nov 15, 2019

提供以下测试用例,注意第二条测试用例,因此 bind 可实现 _.partial(func, [partials]) 类似功能

function f (b) {
  console.log(this.a, b)
}

//=> 3, 4
f.fakeBind({ a: 3 })(4)

//=> 3, 10
f.fakeBind({ a: 3 }, 10)(11)

相关问题:

@shfshanyue shfshanyue added the js label Nov 15, 2019
@shfshanyue
Copy link
Owner Author

shfshanyue commented Nov 16, 2019

最简单的 bind 一行就可以实现,而在实际面试过程中也不会考察你太多的边界条件

Function.prototype.fakeBind = function(obj, ...args) {
  return (...rest) => this.call(obj, ...args, ...rest)
}

测试一下

function f (arg) {
  console.log(this.a, arg)
}

// output: 3, 4
f.bind({ a: 3 })(4)

// output: 3, 4
f.fakeBind({ a: 3 })(4)

@SageSanyue
Copy link

那我再抄一个加强版吧嘻嘻
《JavaScript权威指南》P191 ES3实现bind

if (!Function.prototype.bind) {
  Function.prototype.bind = function(o /*, args */) {
    var self = this, boundArgs = arguments;
    return function () {
      var i, args = [];
      for (i = 1; i < boundArgs.length; i++) {
        args.push(boundArgs[i])
      }
      for (i = 0; i < arguments.length; i++) {
        args.push(arguments[i])
     }
     return self.apply(o, args)
    }
  }
}

@Vi-jay
Copy link

Vi-jay commented May 16, 2022

Function.prototype.fakeBind = function (target, ...args) {
  return (...rest) => this.apply(target, args.concat(rest).slice(0, this.length));
};

@hefeng6500
Copy link

hefeng6500 commented Jun 16, 2022

bind 优化版本:考虑 bind 后返回的函数作为构造函数被 new

Function.prototype.bind = function(context, ...args) {
  const self = this;
  const fn = function(...newArgs) {
    self.apply(this instanceof fn ? this : context, args.concat(newArgs));
  };

  fn.prototype = Object.create(this.prototype);

  return fn;
};

@zhangtuo1999
Copy link

zhangtuo1999 commented Jan 27, 2023

Function.prototype.myBind = function (ctx) {
    ctx ??= globalThis
    ctx = Object(ctx)

    const self = this
    const args = [...arguments].slice(1)

    function bound() {
        self.call(new.target ? this : ctx, ...args)
    }

    bound.prototype = self.prototype
    return bound
}

@Yinzhuo19970516
Copy link

Yinzhuo19970516 commented Apr 3, 2023

Function.prototype._bind(obj,...args){
  obj.fn = this
  return function(...args){
    const r = obj.fn(...args)
    delete obj.fn
    return  r
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants