繼承String物件
Mon, 16 Mar 2009 22:06:01 +0800看到有人問如何繼承javascript內建的String物件,於是動手試了一下。果然,不是想像中的簡單。
粗淺的想法是:
function NewType() { } NewType.prototype = new String;
但是這樣沒辦法使用到繼承的String內建的方法...
看了一下ECMA-262,裡面關於String Native Object的定義中,所有native function的動作第一步都是做ToString。所以試著調整NewType讓他盡量相容看看:
function NewType(str) { this._str = str; this.toString = function() { if(this._str && typeof(this._str)==="string") { return this._str||""; } else { throw("Type Error."); } } } NewType.prototype = new String;
恩...測試了一下,如果使用運算子"+"會出現呼叫valueOf()的錯誤,所以另外加了這個函數的實作,同時也試著給NewType加上一個trim方法,並做測試:
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 \nfrom now on "); alert(b); alert(b+"|"); alert(b.indexOf("co")); alert(b.trim()+ "|"); alert(b.toUpperCase()); alert(b.charAt(3));
ok,這樣就不會出現錯誤了,而且在ff3、ie7、safari、google chrome都可以正確執行。