Skip to content

实现 bind

Function.prototype.bind() 方法与 call 和 apply 不同,该方法返回一个更改过函数执行上下文对象(即 this 指向)的函数。

Code

javascript
Function.prototype.myBind = function (context) {
  const ctx = context ? Object(context) : globalThis;
  const fn = this;
  const args = Array.prototype.slice.call(arguments, 1);
  return function () {
    const newArgs = Array.prototype.slice.call(arguments, 0);
    return fn.apply(ctx, args.concat(newArgs));
  };
};

Test Cases

javascript
require('./bind');

function logAge() {
  return this.age;
}

const obj = {
  age: 18,
};
const bindedLogAge = logAge.myBind(obj);
describe('test bind', () => {
  it('should be undefined', () => {
    expect(logAge()).toBe(undefined);
  });
  it('should be 18', () => {
    expect(bindedLogAge()).toBe(18);
  });
});