Dave Winer posted a lesson-learned tip about JavaScript. Although Java and JavaScript are unrelated languages, they have many similarities.
var d1 = new Date ("March 12, 1994");
var d2 = new Date ("March 12, 1994");
alert (d1 == d2); // false
It seems that JavaScript, like Java, is actually comparing the two Date objects, d1 and d2, to see if they're the same object in memory, not the same value. Since these instance variables are not referencing the same object the alert line of code returns false.
Although, at first blush, this seems unintuitive, it actually allows greater flexibility when making comparisons. If you don't want to compare the two objects, but rather the value of the two objects, then you can simply send the Date object the getTime() message which returns true.
var d1 = new Date ("March 12, 1994");
var d2 = new Date ("March 12, 1994");
alert (d1.getTime() == d2.getTime()); // true
And, finally, to prove my theory to myself...
var d1 = new Date ("March 12, 1994");
var d2 = d1;
alert (d1 == d2); // true
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.