I’m trying to create a set of re-usable objects in javascript and some of the managed-framework paradigms (like .NET) don’t directly translate.
For instance, there is no global getType() method or its equivalent, and there is no default equals() prototype function on Object that even just does a basic reference comparison.
So if I was going to go about creating object definitions, what is the best way to write the comparison function prototype?
e.g. if I started along the lines of the below, am I headed in the right direction or setting myself up for some pain later?
EDIT: Placed code on same line as return as per comment suggestion
function Car(make, model, colour) {
this.make = make;
this.model = model;
this.colour = colour;
}
Car.prototype.equals = function(otherCar) {
// Check that 'otherCar' really is a 'Car' ?
// otherwise the property comparison code below with throw an exception, right?
// How?
// I could just use try / catch, but that could be 'expensive'?
// Property-for-property comparison
try {
return this.make === otherCar.make
&& this.model === otherCar.model
&& this.colour === otherCar.colour;
} catch(err) {
return false;
}
}
Using
try-catchis not necessary here. The return statement does not throw an Exception anyway. Just useIt will always return a boolean value unless you don’t pass anything in the first place. If, however, you wish to have the function return false without any parameters, use
As for the general idea, I think it’s not bad and if you have a lot of comparisons to make. This confines you back into tight frames which depending on reasons might be good, but at the same time you sacrifice freedom.
EDIT
try-catchblock was partially fixed in the question. Added improvements pointed out in comments.