gpt4 book ai didi

javascript - String.prototype.replace === String.replace

转载 作者:行者123 更新时间:2023-11-28 10:08:40 26 4
gpt4 key购买 nike

当我使用 call()apply() 时,我遇到了问题。

console.log(String.prototype.replace === String.replace);//false

我认为String.replace应该与String.prototype.replace相等,因为它们是相同的Object。

但是,它们彼此不同。

当我运行下面的代码时会发生什么:

var s = "a b c";
String.replace.call(s,'a','A');//return "a"

为什么这段代码不抛出错误,而是返回一个值?

最佳答案

我认为这里有很多混合信息。首先我们要澄清的是String构造函数does not have a replace method .

因此,无论 Firefox 中的 String.replace 是什么,它都是非标准的,因此您应该远离它。 A quick test in Chrome显示 String.replace 确实不存在。

不幸的是,我无法告诉您 String.replace 在 Firefox 中来自何处。 The documentation没有提到它。但它似乎不是继承的属性,因为 String.hasOwnProperty('replace') 返回 true

<小时/>

现在谈谈您问题中的一些要点:

I think String.replace should be equal with String.prototype.replace, because they are the same Object.

显然不是。如果是,它将返回true。另外:String !== String.prototype.

字符串实例使用的replace方法是String.prototype.replace。因此,如果您想使用 callapply,请使用此方法。

Why doesn't this code throw an error, but return a value?

为了回答这个问题,我们必须知道该方法正在做什么。也许查看 Firefox 或 Spidermonkey 源代码可以提供一些信息。

如果您对原型(prototype)继承的工作原理感到困惑,请查看 MDN JavaScript Guide -Details of the object modelInheritance revisited .

关于javascript - String.prototype.replace === String.replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com