bind 函数多次调用会已第一次绑定的 this 为准,softbind 已最后一次绑定传入的 this 为准

    1. Function.prototype.softBind = function (obj, ...rest) {
    2. const fn = this
    3. const bound = function (...args) {
    4. //如果this不存在,或者this指向window或global,就指向开头绑定的
    5. const o = !this || this === (window || global) ? obj : this
    6. return fn.apply(o, [...rest, ...args])
    7. }
    8. bound.prototype = Object.create(fn.prototype)
    9. return bound
    10. }
    11. function foo() { console.log(this.name); }
    12. let obj = { name: "obj" };
    13. obj2 = { name: "obj2" };
    14. obj3 = { name: "obj3" };
    15. let fooBJ = foo.softBind(obj);
    16. fooBJ(); // name: obj 这个时候软绑定已经生效了,this绑定到obj上
    17. obj2.foo = foo.softBind(obj);
    18. obj2.foo(); //name: obj2 这里已经的this隐式绑定到obj2上了
    19. fooBJ.call(obj3); // name: obj3 这里this被硬绑定到obj3上了
    20. setTimeout(obj2.foo, 100); // name: obj 软绑定了最初的obj