3 回答

TA貢獻1785條經(jīng)驗 獲得超4個贊
由于每個人都投了我的另一個答案,我想發(fā)布概念代碼的證明,其實際上按預(yù)期工作。
這已在chrome和IE中測試過。
//Operator Overloadingvar myClass = function () {//Privatesvar intValue = Number(0), stringValue = String('');//Publicsthis.valueOf = function () { if (this instanceof myClass) return intValue; return stringValue;}this.cast = function (type, call) { if (!type) return; if (!call) return type.bind(this); return call.bind(new type(this)).call(this);}}//Derived classvar anotherClass = function () {//Store the base referencethis.constructor = myClass.apply(this);var myString = 'Test', myInt = 1;this.valueOf = function () { if (this instanceof myClass) return myInt; return myString;}}//Testsvar test = new myClass(),anotherTest = new anotherClass(),composed = test + anotherTest,yaComposed = test.cast(Number, function () { return this + anotherTest}),yaCComposed = anotherTest.cast(Number, function () { return this + test;}),t = test.cast(anotherClass, function () { return this + anotherTest}),tt = anotherTest.cast(myClass, function () { return this + test;});debugger;
如果有人愿意提供技術(shù)解釋為什么這不夠好我會很高興聽到它!

TA貢獻2080條經(jīng)驗 獲得超4個贊
據(jù)我所知,Javascript(至少現(xiàn)在存在)不支持運算符重載。
我能建議的最好的方法是從其他幾個方法制作新的配額對象的類方法。這是我的意思的一個簡單例子:
// define an example "class"
var NumClass = function(value){
this.value = value;
}
NumClass.prototype.toInteger = function(){
return this.value;
}
// Add a static method that creates a new object from several others
NumClass.createFromObjects = function(){
var newValue = 0;
for (var i=0; i<arguments.length; i++){
newValue += arguments[i].toInteger();
}
return new this(newValue)
}
并使用它像:
var n1 = new NumClass(1);
var n2 = new NumClass(2);
var n3 = new NumClass(3);
var combined = NumClass.createFromObjects(n1, n2, n3);
添加回答
舉報