Hello Ondrej,
thanks for trying out restrict mode and providing your feedback!
12 okt 2012 kl. 09:15 skrev Ondřej Žára <
ondre...@gmail.com>:
> consider the following code snippet:
>
> String.prototype.x = function() { return this + "x"; }
>
> What is the result of running this code through restrict mode? It depends on typeof(this) within the method.
>
> Chrome - strict mode - typeof(this) == "object"
> Chrome - non-strict mode - typeof(this) == "object"
> Firefox - strict mode - typeof(this) == "string"
> Firefox - non-strict mode - typeof(this) == "object"
What you've noticed is the semantic change of boxed/primitive value this in ES5 strict mode. I can't reproduce your mismatch between Chrome and Firefox. Your Firefox example shows the result of running in a browser that support ES5, your Chrome example running in one that doesn't.
> As long as typeof(this) != "string", restrict mode throws an exception (incorrectly, imho).
That is per design. "+ is restricted to primitive strings and numbers (in any combination)". JS primitives and boxed values mix very badly. The remediation is very simple though - just explicitly convert the boxed value to a primitive, in your case via String(this):
String.prototype.x = function() { return String(this) + "x"; }
I consider ES5 strict mode primive-this harmful and a design mistake because the (non-throwing) semantics of ES5 strict mode is no longer a subset of non-strict mode. Check out slide 41 of <
http://blog.lassus.se/files/javascript_the_subsets_we_use_webshaped.pdf> for a concrete example of why.
Cheers,
/Olov