JavaScript的bind函数实现

3

我希望为不支持 bind 函数的浏览器创建 JavaScript bind 函数的 polyfill。请问有人知道 bind 函数在 JavaScript 中是如何实现的吗?


3
以下是Function.prototype.bind()方法的Polyfill实现,可在不支持该方法的旧版浏览器中使用:if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== 'function') { throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }要点解释:
  • 该Polyfill会检查当前环境是否已有bind()方法的原生实现,如果没有则定义一个Function.prototype.bind属性并赋值为新的实现。
  • bind()方法可以接收一个参数oThis作为绑定函数的this对象,并返回一个新的函数作为绑定结果。调用绑定函数时,将传入的参数与绑定函数的参数拼接起来一并传入执行。
  • 当绑定函数被用于构造函数时,原始函数的prototype属性应该复制到绑定函数的原型上,以便继承原始函数的原型链。
- VLAZ
6个回答

5
在最简单的情况下,bind只是apply的一个包装器:
function bind(fn, thisObj) {
  return function() {
    return fn.apply(thisObj, arguments);
  }
}

3

使用apply实现bind的基本功能。我称此方法为myBind,将其添加到函数原型中,以便任何函数都可以访问:

函数实现

Function.prototype.myBind = function() {
const callerFunction = this;
const [thisContext, ...args] = arguments;
return function() {
    return callerFunction.apply(thisContext, args);
}

用法: 可以作为一个本地绑定函数,接受上下文和参数。

function testMyBind(favColor) {
   console.log(this.name, favColor); // Test, pink
}

const user = {
   name: 'Test'
}

const bindedFunction = testMyBind.myBind(user, 'pink');
bindedFunction();

2
为了保持简单,在使用现代JavaScript时:
Function.prototype.bind = function () {
    return () => this.call(...arguments);
};

这就是全部内容了。

1

使用apply实现基本功能。绑定函数和被绑定的函数都可以接受参数。

Function.prototype.bindPolyfill = function (obj, ...args) {
  const func = this;
  return function (...newArgs) {
    return func.apply(obj, args.concat(newArgs));
  };
};

使用方法:

const employee = { id: '2'};

const getEmployee = function(name, dept){
   console.log(this.id, name, dept);
};

const employee2 = getEmployee.bindPolyfill(employee, 'test');

employee2('Sales');


0
Function.prototype.bindPolyfill = function (newThis, ...args) {
  return (...newArgs) => {
    return this.apply(newThis, [...args, ...newArgs]);
  };
};

// Usage
const employee = { id: '2' };

const getEmployee = function (name, dept) {
  console.log(this.id, name, dept);
};

const employee2 = getEmployee.bindPolyfill(employee, 'test');

employee2('Sales'); // 2 test Sales

0
Function.prototype.customBind = function(ctx, ...args) {
    const fn = this;

    return function() {
        return fn.apply(ctx, args);
    }
}

一个简单的解决方案

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接