是否有在Javascript中实现对象算法的本机支持?

时间:2017-02-05 15:31:11

标签: javascript syntax

想想Date()对象:

thisDate = new Date()
thatDate = new Date()
thisDate - thatDate //returns some date object

我是否可以制作一些对象,比如说Clovers()

theseClovers = new Clovers();
theseClovers.count = 10;
thoseClovers = new Clovers();
thoseClovers.count = 4;

theseClovers - thoseClovers; //returns b = new Clovers(); b.count = 6

这是我设想的方式(但完全是假设的):

function Clovers(){
    onSubtract(b){
        if(b instanceOf someClass){
            return this.count - b.count
        }
    }
}

1 个答案:

答案 0 :(得分:2)

function Clovers(val){
   this.count=val || 0;
}
Clovers.prototype.valueOf=function(){
 return this.count;
};

所以它会非常相似:

alert(new Clovers(new Clovers(10)-new Clovers(5)).count);
//or long written:
var a=new Clovers(10);
var b=new Clovers(4);
var c=new Clovers(a-b);
alert(c.count);

但是,为此设置自定义添加功能可能更好,类似于Array.prototype.concat:

 Clovers.prototype.concat=function(clover){
   return new Clovers(this.count-clover.count);
 };

像这样使用:

var a=new Clovers(10);
var b=new Clovers(5);
var c=a.concat(b);
alert(c.count);

感谢Pointy和Karl-JohanSjögren的想法...