2016-04-23 54 views

回答

2

運算符重載不能正常支持在JavaScript /打字稿。 如果您嘗試調用某個類,則無法定義調用的函數(構造函數除外)。

+0

確實沒有真正的操作重載,但你仍然可以做一些 - 當然是有限的 - 類似於操作重載的東西[這裏是一個例子](https://jsfiddle.net/gvo86g6c/)。 –

2

有沒有辦法在打字稿實現這一目標?

爲什麼不。因爲它可以用普通的JavaScript來完成,所以在TypeScript中也很容易實現。與功能幾乎一樣,範圍是我們方法的關鍵字。 當然,構造函數會被誤用爲閉包而不會創建會響應Container通過typeof運營商。這樣的工廠函數將返回另一個函數,然後將其用作構造函數的封閉初始值的getter/setter。

打字稿例如...

class Container { 

    constructor(storageValue: any) { 
     return (function (value: any) { 

      if (arguments.length !== 0) { 
       storageValue = value; 
      } 
      return storageValue; 
     }); 
    } 
} 

...在普通的JavaScript ...

var Container = (function ContainerClass() { 

    var Constructor = (function Container (storageValue) { 
     return (function (value) { 

      if (arguments.length !== 0) { 
       storageValue = value; 
      } 
      return storageValue; 
     }); 
    }); 
    return Constructor; 

}()); 

var a = new Container(24); 

console.log("a() : ", a()); // 24 
console.log("a(4) : ", a(4)); // 4 
console.log("a() : ", a()); // 4 

var b = new Container(72); 

console.log("b() : ", b()); // 72 
console.log("b(5) : ", b(5)); // 5 
console.log("b() : ", b()); // 5 

console.log("a() : ", a()); // 4 
+1

而不是'if(UNDEFINED_VALUE!== value){'最好使用arguments.length === 0',因爲'a()'和'a(undefined)'是兩個不同的東西。 –

+0

你顯然是對的。 –

+0

這不是類型安全的。如果您在任何地方放置「任何」,使用TypeScript是毫無意義的。 – Yaroslav

相關問題