gpt4 book ai didi

javascript - 为自定义对象声明制作 JavaScript 'equals' 方法原型(prototype)是一种好习惯吗?如果是的话,怎么做?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:21:22 24 4
gpt4 key购买 nike

我正在尝试在 javascript 中创建一组可重复使用的对象,但一些托管框架范例(如 .NET)不会直接转换。

例如,没有全局的 getType() 方法或其等效方法,也没有默认的 Object 上的 equals() 原型(prototype)函数,甚至只是做一个基本的引用比较。

因此,如果我打算着手创建对象定义,编写比较函数原型(prototype)的最佳方式是什么?

例如如果我按照下面的路线开始,我是在朝着正确的方向前进,还是在为以后的痛苦做好准备?

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

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;

它总是会返回一个 bool 值,除非你一开始就没有传递任何东西。但是,如果您希望函数不带任何参数返回 false,请使用

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

至于总体思路,我觉得还不错,如果你有很多比较的话。这将你限制在严格的框架内,这取决于原因可能是好的,但同时你牺牲了自由。

EDIT try-catch block 已在问题中部分修复。添加了评论中指出的改进。

关于javascript - 为自定义对象声明制作 JavaScript 'equals' 方法原型(prototype)是一种好习惯吗?如果是的话,怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7254908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com