【问题标题】:You don't know JS book, softening 'this' binding你不懂 JS 书,软化 'this' 绑定
【发布时间】:2019-04-14 13:44:45
【问题描述】:

YDKJS 这本书包含一个描述soft binding utiliy 的部分:

if (!Function.prototype.softBind) {
    Function.prototype.softBind = function(obj) {
        var fn = this,
            curried = [].slice.call( arguments, 1 ),
            bound = function bound() {
                return fn.apply(
                    (!this ||
                        (typeof window !== "undefined" &&
                            this === window) ||
                        (typeof global !== "undefined" &&
                            this === global)
                    ) ? obj : this,
                    curried.concat.apply( curried, arguments )
                );
            };
        bound.prototype = Object.create( fn.prototype );
        return bound;
    };
}

我无法理解这条线:curried.concat.apply( curried, arguments )。为什么我们要将已经柯里化的论点与 arguments 对象,而不是简单地使用 curried 数组:

...
        ) ? obj : this,
        curried
    );
};
bound.prototype = Object.create( fn.prototype );
...

【问题讨论】:

  • 你了解bind 是如何处理参数的吗?
  • 这是一个绝对可怕的实现,无论它试图实现什么功能。最好忘记它。
  • 不,bind 的工作原理完全相同:const f = console.log.bind(console, "Hello"); f("World");
  • 请注意,curried 来自对softBind 的调用的arguments(如我的示例中的“Hello”),而另一个arguments 来自对绑定函数的调用(就像我的例子中的“世界”)。
  • 用现代语法编写(省略了接收者):function bind(fn, ...args1) { return function(...args2) { return fn(...args1, ...args2); }; }

标签: javascript


【解决方案1】:

当你调用一个绑定函数时,它首先传递绑定的参数,然后是从调用到绑定版本的新参数。

function log(a, b, c, d, e) {
    console.log([a, b, c, d, e]);
}

log(1, 2, 3, 4, 5);

const bound = log.bind(null, 1, 2, 3);

bound(4, 5);

如果您没有连接 bound 和 new 参数,那么您只能记录 1、2 和 3。

【讨论】:

  • 你可能想补充一点,实现被破坏了,当你传递一个数组时它不起作用。
猜你喜欢
  • 2014-10-17
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2018-09-06
  • 2013-10-25
  • 2017-10-13
相关资源
最近更新 更多