覆盖JavaScript中比较运算符的默认行为 [英] Override default behavior of comparison operators in JavaScript

查看:101
本文介绍了覆盖JavaScript中比较运算符的默认行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义Javascript类(使用 John Resig的简单Javascript继承创建) 。我希望能够使用 == < ,<$ c来比较此类的两个实例$ c>> ,> = < = 符号。

I have a custom Javascript class (created using John Resig's Simple Javascript Inheritance). I want to be able to compare two instances of this class, using the ==, <, >, >=, and <= symbols.

如何覆盖自定义类的比较器?

How do I override the comparators of my custom class?

推荐答案

这不能以你暗示它应该被完成的方式来完成(尽管那会很好)。我看到这样做的最好方法是在原型上实现一组方法,就像比较一样:

this cannot be done in the way that you are implying it should be done (though that would be sweet). The best way I have seen this done is to implement on the prototype a set of methods to act like comparatives:

gte : function( obj ){ // greater than or equal
  // return custom comparison with this as the object comparable on the left
},
gt : function( obj ){...}, // greater than but not equal
eq : function( obj ){...}, // equal to
// etc.

我今天在工作中考虑了这个问题,并且有另一种方法可以利用标准比较运算符但是有自定义对象比较。诀窍是在对象上有一个表示可比状态的属性(getter)。这将要求在给定相同的可比较属性的情况下,对象的所有实例都评估为相同的数值。作为一个例子,让我们谈谈向量:

I was thinking about this problem somemore at work today and there is an alternate way to take advantage of the standard comparison operators but have custom object comparisons. The trick would be to have a property (getter) on the object that represented the comparable state. This would require that all instances of the object evaluate to the same numeric value given the same comparable properties. As an example let's talk vectors:

function Vector(x,y,z){
  this.comp = function(){
    // assuming these are floats you may wish to create a comparable level of
    // precision. But this gets the point across.
    return x + (y * 10) + (z * 100);
  }
}

然后设置向量时:

var v1 = new Vector(1,1,1);
var v2 = new Vector(1,0,1);
v1.comp() > v2.comp() // true

这当然只能处理可以对象的对象被分解为值的简单数值表达式,但好处是获得基本效果的实现代码非常低,甚至可以使对象本身成为返回其组件的数字表达式的函数。

This only works of course if you are dealing with objects that can be broken down into simple numeric expression of value, but the upside is that the implementation code to get the basic effect is pretty low and you could even go so far as to make the object itself a function that returns the numeric expression of it's component parts.

function Vector(x,y,z){
  var v = function v(){
    return v.x + (v.y * 10) + (v.z * 100);
  }
  v.x = x;
  v.y = y;
  v.z = z;
  return v;
}

现在,通过简单的数字比较,您可以获得对象的所有好处,甚至可以有点简洁。

now you have all the benefits of the object with easy numeric comparisons and it's even kinda terse.

这篇关于覆盖JavaScript中比较运算符的默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆