On 2009.07.07., at 22:37, Greg Brown wrote:

js> new String("a") == new String("a")
false
js> new Number(2) == new Number(2)
false
...
Which is due to the fact that if any of the operands is a JS primitive type (i.e. string, number) then the other will be coerced into a primitive value and then the equality among primitive values will be used instead. Yeah, it's bloody un-intuitive, but that's the way JS works. Nothing you can do about it.

That makes sense. But what if one or both of the operands were Java objects? e.g. replace the JS native String above with java.lang.String:

js> new java.lang.String("a") == new java.lang.String("a")

If this expression evaluated to true, it wouldn't violate JS equality semantics, since JS values are not involved.

Except they are. These values belong to the JavaScript "object" type:

js> typeof(new java.lang.String("a"))
object

They *have* to be exposed as such, since in JavaScript, every value must belong to one of the JS types, and the *only* types in JS are these: Undefined, Null, Boolean, Number, String, and Object [1].

Therefore, the == operator will compare two JS objects, for which the only valid comparison is the reference comparison.

Groovy invokes the corresponding Java method on the left-hand operand. So, if a Java object was on the left, equals() could be called, and if a JS object was on the left, then JS reference equality could be used...

Well, Groovy is a language designed from the start for tight cooperation with Java. JavaScript - despite the name, is not. Not at all. For long time, most of its implementations were written in C. We're doing what we can with Rhino, but there's a good deal of language semantics mismatch that we just can't hide.

Attila.

[1] Actually, there's also three other value types: Reference, List, and Completion, but they can not ever be observed by a JS program itself, they're internal to the runtime. Actually, they need not even be implemented proper by a JS runtime, but a conformant JS runtime must behave in certain calculations as if it operated on them. They're primarily a specification device.

--
twitter: http://twitter.com/szegedi
weblog: http://constc.blogspot.com
home: http://www.szegedi.org

_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino

Reply via email to