3 回答
TA贡献1785条经验 获得超4个赞
由于每个人都投了我的另一个答案,我想发布概念代码的证明,其实际上按预期工作。
这已在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;
如果有人愿意提供技术解释为什么这不够好我会很高兴听到它!
TA贡献2080条经验 获得超4个赞
据我所知,Javascript(至少现在存在)不支持运算符重载。
我能建议的最好的方法是从其他几个方法制作新的配额对象的类方法。这是我的意思的一个简单例子:
// 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);
添加回答
举报