When I use call() or apply(), I got a problem.
console.log(String.prototype.replace === String.replace);//false
I think String.replace should be equal with String.prototype.replace, because they are the same Object.
However,they are different from each other.
What happens when I run the code below:
var s = "a b c";
String.replace.call(s,'a','A');//return "a"
Why doesn’t this code throw an error, but return a value?
I think there is a lot of mixed information here. First of all we have to clarify that the
Stringconstructor function does not have areplacemethod.So, whatever
String.replaceis in Firefox, it is non-standard and therefore you should stay away from it. A quick test in Chrome shows thatString.replaceindeed does not exist there.Unfortunately I cannot tell you where
String.replacecomes from in Firefox. The documentation does not mention it. But it seems that it is not an inherited property, asString.hasOwnProperty('replace')returnstrue.Now to some points in your question:
Obviously they are not. If they were, it would return
true. Also:String !== String.prototype.The
replacemethod which is used by the string instances isString.prototype.replace. So if you want to usecallorapply, you them on this method.In order to answer that, we would have to know what that method is doing. Maybe a look at the Firefox or Spidermonkey source provides some information.
If you are confused about how prototype inheritance works, have a look at the MDN JavaScript Guide – Details of the object model and Inheritance revisited.