作者fillano (冒牌費大公)
看板Ajax
標題Re: [問題] 如何對 String 實施繼承?
時間Mon Mar 16 01:34:21 2009
嘗試這樣做,讓NewType與String相容:
<html>
<body>
<script>
function NewType(str) {
this._str = str;
this.toString = function() {
return this.valueOf();
}
this.valueOf = function() {
if(this._str && typeof(this._str)==="string") {
return this._str||"";
} else {
throw("Type Error.");
}
}
}
NewType.prototype = new String;
NewType.prototype.trim = function() {
return this.replace(/^\s+|\s+$/, '');
};
var b = new NewType("a new day is coming ");
alert(b);
alert(b+"|");
alert(b.indexOf("co"));
alert(b.trim()+ "|");
alert(b.toUpperCase());
</script>
</body>
</html>
看起來需要做幾件事:
1. constructor (也就是NewType這個function)需要模仿String來傳入參數
2. 必須用自己的方法實作toString以及valueOf方法
alert(b)會用到toString
alert(b+"|")會用到valueOf
String的native方法以及你用prototype掛上去的方法,好像都會呼叫toString。
我沒仔細看ECMA-262,不過這樣是可以跑的。
--
Sapere Aude! 這就是啟蒙運動的口號!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 60.248.166.83
1F:推 legnaleurc:嗯...的確是可以動了,不過如果使用 03/16 14:03
2F:→ legnaleurc:new String( ... )或是null來初始化NewType 03/16 14:04
3F:→ legnaleurc:行為就會和String不一樣QQ 03/16 14:04
4F:→ legnaleurc:第二種狀況我是直接丟 exception 03/16 14:05
5F:→ legnaleurc:但是第一種似乎不能用typeof來看 03/16 14:06
6F:→ fillano:如果不用new NewType("xxx")的方式來初始化,那幹麼要繼承 03/16 15:23
7F:→ fillano:?用composite就好了阿? 03/16 15:24
8F:→ fillano:嗯嗯,看了一下ecma-262,看起來關鍵是實作valueOf跟 03/16 22:28
9F:→ fillano:toString,這樣繼承的函數就可以執行,constructor傳進來 03/16 22:29
10F:→ fillano:的參數,只要合理地處理,讓valueOf跟toString可以正確執 03/16 22:30
11F:→ fillano:行應該就可以跑了。String物件的這些方法,動作的第一步都 03/16 22:31
12F:→ fillano:是呼叫ToString,而使用"+"來做字串運算時,會呼叫valueOf 03/16 22:32
13F:→ fillano:,所以只要這兩個正確運作就可以呼叫從String繼承來的方法 03/16 22:33
14F:推 legnaleurc:喔喔,也就是說因為沒有處理自己的toString 03/16 23:03
15F:→ legnaleurc:才會失敗 謝謝指教!:P 03/16 23:03
16F:推 gpmm:推一下費大,這篇實在有 m 的價值! 03/18 22:06