Is it possible to create custom operators in JavaScript?

后端 未结 9 1915
暖寄归人
暖寄归人 2020-12-03 04:20

During the Math classes we learned how to define new operators. For example:

(ℝ, ∘), x ∘ y = x + 2y

This defines law. For any r

9条回答
  •  無奈伤痛
    2020-12-03 05:08

    No. JavaScript does not support operator overloading . but you can make a class method for doing this

    var mathClass = function(value){
       this.value = value;
    }
    
    mathClass.prototype.toLaw = function(){
       return 2 * this.value;
    }
    
    var y = new mathClass(2)
    2 + y.toLaw(); //2 + 2 * y
    

提交回复
热议问题