Re: [問題] 如何對 String 實施繼承?

看板Ajax作者 (冒牌費大公)時間16年前 (2009/03/16 01:34), 編輯推噓3(3013)
留言16則, 3人參與, 最新討論串2/2 (看更多)
嘗試這樣做,讓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

03/16 14:03, , 1F
嗯...的確是可以動了,不過如果使用
03/16 14:03, 1F

03/16 14:04, , 2F
new String( ... )或是null來初始化NewType
03/16 14:04, 2F

03/16 14:04, , 3F
行為就會和String不一樣QQ
03/16 14:04, 3F

03/16 14:05, , 4F
第二種狀況我是直接丟 exception
03/16 14:05, 4F

03/16 14:06, , 5F
但是第一種似乎不能用typeof來看
03/16 14:06, 5F

03/16 15:23, , 6F
如果不用new NewType("xxx")的方式來初始化,那幹麼要繼承
03/16 15:23, 6F

03/16 15:24, , 7F
?用composite就好了阿?
03/16 15:24, 7F

03/16 22:28, , 8F
嗯嗯,看了一下ecma-262,看起來關鍵是實作valueOf跟
03/16 22:28, 8F

03/16 22:29, , 9F
toString,這樣繼承的函數就可以執行,constructor傳進來
03/16 22:29, 9F

03/16 22:30, , 10F
的參數,只要合理地處理,讓valueOf跟toString可以正確執
03/16 22:30, 10F

03/16 22:31, , 11F
行應該就可以跑了。String物件的這些方法,動作的第一步都
03/16 22:31, 11F

03/16 22:32, , 12F
是呼叫ToString,而使用"+"來做字串運算時,會呼叫valueOf
03/16 22:32, 12F

03/16 22:33, , 13F
,所以只要這兩個正確運作就可以呼叫從String繼承來的方法
03/16 22:33, 13F

03/16 23:03, , 14F
喔喔,也就是說因為沒有處理自己的toString
03/16 23:03, 14F

03/16 23:03, , 15F
才會失敗 謝謝指教!:P
03/16 23:03, 15F

03/18 22:06, , 16F
推一下費大,這篇實在有 m 的價值!
03/18 22:06, 16F
文章代碼(AID): #19lJmWbO (Ajax)
文章代碼(AID): #19lJmWbO (Ajax)