当我使用call()或apply()时,我遇到了一个问题。
console.log(String.prototype.replace === String.replace);//false我认为String.replace应该等同于String.prototype.replace,因为它们是同一个对象。
然而,它们是不同的。
当我运行下面的代码时会发生什么:
var s = "a b c";
String.replace.call(s,'a','A');//return "a" 为什么这段代码不抛出错误,而是返回值呢?
发布于 2011-10-18 22:24:44
我认为这里有很多混杂的信息。首先,我们要澄清的是String构造函数does not have a replace method。
所以,无论火狐中的String.replace是什么,它都是非标准的,因此你应该远离它。A quick test in Chrome表明String.replace确实不存在于此。
不幸的是,我无法告诉你String.replace在火狐中是从哪里来的。The documentation没有提到这一点。但它似乎不是继承的属性,因为String.hasOwnProperty('replace')返回true。
现在来谈谈你问题中的一些要点:
我认为
String.replace和String.prototype.replace应该是一样的,因为它们是同一个对象。
显然他们不是。如果是,它将返回true。还有:String !== String.prototype。
string实例使用的replace方法是String.prototype.replace。因此,如果你想使用call或apply,你可以使用这个方法。
为什么这段代码不抛出错误,而是返回值?
为了回答这个问题,我们必须知道这个方法在做什么。也许看一看Firefox或Spidermonkey的源代码就能提供一些信息。
如果您对原型继承的工作原理感到困惑,可以看看MDN JavaScript Guide - Details of the object model和Inheritance revisited。
发布于 2011-10-18 21:11:37
这将是真的:
(new String()).replace === String.prototype.replace这将不会:
String.prototype.replace === String.replaceString是一个构造函数,这只是一个函数。
String.prototype是一个对象,使用new String()创建的其他对象将在没有属性的情况下搜索这些属性。
new String()将创建一个新对象。请考虑以下内容:
var s = new String();
s.replace(...);实际上,s没有replace方法。通过其构造函数has的原型,这就是调用此方法将会成功的原因。
发布于 2011-10-18 21:12:37
replace()方法的语法是string.replace(),其中string必须是字符串,而不是字符串对象。
https://stackoverflow.com/questions/7807677
复制相似问题