javascript - 使用原型(prototype) apply vs this 来调用函数

标签 javascript prototype this

关于MDN String页面他们有一个 polyfill String.includes 的例子。

String.prototype.includes = function() {'use strict';
    return String.prototype.indexOf.apply(this, arguments) !== -1;
};

他们使用 String.prototype.indexOf.apply 与直接在 this 上调用 indexOf 有什么原因吗?

String.prototype.includes = function(searchString, position) {'use strict';
    return this.indexOf(searchString, position) !== -1;
};

最佳答案

答案是使用 this.indexOf 的 polyfill 版本不符合 spec for String.prototype.includes ,它允许 this 是任何可转换为字符串的东西:

If searchString appears as a substring of the result of converting this object to a String...

例如,includesthis 可以是一个数字:

<< String.prototype.includes.call(1, '1')
>> true

这类似于 String.prototype.indexOf,根据 spec也不要求它的 this 是一个字符串。

<< String.prototype.indexOf.call(1, '1')
>> 0

如果 includes 是按照 OP 建议的 this.indexOf 实现的:

String.prototype.includes = function(searchString, position) {'use strict';
    return this.indexOf(searchString, position) !== -1;
};

然后调用 includes 并使用非字符串 this,正如规范所允许的那样,会产生一个运行时错误:

<< String.prototype.includes.call(1, '1')
>> TypeError: undefined is not a function

而 MDN polyfill:

String.prototype.includes = function() {'use strict';
    return String.prototype.indexOf.apply(this, arguments) !== -1;
};

可以正常工作,利用 String.prototype.indexOfthis 也不必是字符串这一事实:

<< String.prototype.includes.call(1, '1')
>> true

所以我想 MDN polyfill 是这样写的,不是为了防止 indexOf 方法在某些特定的字符串对象上被覆盖,或者作为一种简写以避免必须列出参数,或者由于一些 Crockfordian 偏爱 prototype.apply 习惯用法,而是为了正确实现规范。

关于javascript - 使用原型(prototype) apply vs this 来调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28642705/

相关文章:

javascript - 如何使用 jquery 定位第一个 div?

对某些项目进行 Javascript 验证

javascript - 在 Protractor 中验证测试结果(非 "expect"函数)

javascript - 原型(prototype)问题

javascript原型(prototype)循环for in array

javascript - 如何将任何给定表列的值拆分为分隔符处的新行

javascript - 构造函数 - 在简单的命名空间 - Javascript

javascript - jQuery 回调 - 严格违反

javascript - 为什么回调函数中 "this"指向 "window Object"呢?

javascript - 在函数 javascript dojo 工具包中使用 this 关键字