【问题标题】:Trying to Implement Python-Style len() in JavaScript尝试在 JavaScript 中实现 Python 风格的 len()
【发布时间】:2016-05-26 21:00:51
【问题描述】:

我已经阅读了很多关于 JavaScript 中的 call()bind() 的内容,特别是关于 MDN article创建快捷方式部分。

我正在尝试在 JS 中实现以下 Python 风格的函数:

var arr = [1,2,3];
len(arr); // 3

我确实意识到这是一个人为的例子,但我正试图围绕这些方法展开我的头脑。以下是我的实现方式:

var len = Function.prototype.call.bind( Array.prototype.slice.length );
len([1,2,3]);

当我运行它时,我得到:

len([1,2,344])
^

TypeError: len is not a function
    at Object.<anonymous> (/private/var/folders/j6/3fs5_k3n17z_0j2xrwj6sphw0000gn/T/CodeRunner/Untitled 11.js:2:1)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

我在这里缺少什么来了解它是如何工作的?

【问题讨论】:

    标签: javascript python call bind apply


    【解决方案1】:

    当您在代码中设置变量len 时,实际上是在将len 设置为函数Function.prototype.call 的副本,其中this(上下文)为Array.prototype.slice.length

    我认为您误解了 bind() 的用法。假设我有一个函数len

    var len = function() {
        return this.length;
    };
    

    而你想得到一个数组的长度:

    len.call([1,2,3]);
    

    在这种情况下,len 中的this 是数组[1,2,3],因为我们使用call 来提供this。假设我们想将该数组永久绑定到该函数并将其存储在我们可以随时使用的变量中:

    var myArrayLen = len.bind([1,2,3]);
    

    现在,myArrayLen 基本上是 len 的副本,与 this[1,2,3] 永久绑定。如果我们调用它,它会返回 3。

    在您的示例中,Array.prototype.slice.length 实际上是函数Array.prototype.slice 的长度,它对应于number of arguments that can be passed to the function

    没有内置的 length() 函数,因此按照您(诚然)人为设计的示例,我们只需要创建一个提供长度的函数,将其添加到数组原型中,并使用 Function.prototype.apply.bind(); 绑定它:

    Array.prototype.len = function () { return this.length; };
    var len = Function.prototype.apply.bind(Array.prototype.len);
    len([1,2,3]); // 3
    

    【讨论】:

    • 谢谢,但这不允许纯len() 函数的灵活性。做len.call(arr) 不是我的选择,因为我不需要使用call()。我应该能够事先定义调用,这样我只需要函数调用len。此外,最后一个示例不起作用,因为它没有考虑到其他可迭代对象,如 argumentsstrings,这应该能够工作。
    • 我意识到我错过了,并在底部添加了一个编辑 - 这次我做对了吗?
    • 非常酷。非常感谢你。您能否将我链接到与Function.prototype.apply 相关的任何对您有帮助的文章?我仍然很不理解这是如何工作的。出于某种原因,Array.prototype.slice.call(str)String.prototype 和其他内置原型概念对我来说很有意义。出于某种原因,Function.prototype 概念让我大吃一惊。
    • 我推荐You Don't Know JS: this & Object Prototypes。如果你喜欢那本书,我强烈推荐整个系列。它很短。也许this article too。不过,您在 MDN 上走在了正确的轨道上,如果您继续阅读并尝试它,它就会成功。
    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2020-10-01
    相关资源
    最近更新 更多