为自定义对象声明原型化一个JavaScript’equals’方法是不错的做法,如果是这样的话?

我正在尝试在
javascript中创建一组可重用的对象,而某些托管框架范例(如.NET)不能直接翻译.

例如,没有全局getType()方法或它的等价物,并且Object上没有默认的equals()原型函数,甚至只进行基本的参考比较.

因此,如果我要创建对象定义,那么编写比较函数原型的最佳方法是什么?

例如如果我沿着下面的方向开始,我是朝着正确的方向前进还是为了以后的某些痛苦而努力?

编辑:根据评论建议将代码放在返回的同一行

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;

    }
}

最佳答案 这里不需要使用try-catch.无论如何,return语句不会抛出异常.只是用

    return otherCar !== null &&
        this.make === otherCar.make
        && this.model === otherCar.model
        && this.colour === otherCar.colour;

除非你没有首先传递任何东西,否则它将始终返回一个布尔值.但是,如果您希望函数在没有任何参数的情况下返回false,请使用

    return typeof otherCar !== 'undefined' &&
        otherCar !== null &&
        this.make === otherCar.make
        && this.model === otherCar.model
        && this.colour === otherCar.colour;

至于一般的想法,我认为这并不坏,如果你有很多比较.这会将你限制在紧密的框架中,这取决于原因可能是好的,但同时你牺牲了自由.

EDIT try-catch块在问题中得到了部分修复.添加了评论中指出的改进.

点赞