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 referen开发者_如何学编程ce 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-catch
is not necessary here. The return statement does not throw an Exception anyway. Just use
return otherCar !== null &&
this.make === otherCar.make
&& this.model === otherCar.model
&& this.colour === otherCar.colour;
It 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
return typeof otherCar !== 'undefined' &&
otherCar !== null &&
this.make === otherCar.make
&& this.model === otherCar.model
&& this.colour === otherCar.colour;
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-catch
block was partially fixed in the question. Added improvements pointed out in comments.
精彩评论