关于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...
例如,includes
的this
可以是一个数字:
<< 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.indexOf
的 this
也不必是字符串这一事实:
<< 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/