Re: [問題] 如何對 String 實施繼承?
嘗試這樣做,讓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
03/16 14:04, 2F
→
03/16 14:04, , 3F
03/16 14:04, 3F
→
03/16 14:05, , 4F
03/16 14:05, 4F
→
03/16 14:06, , 5F
03/16 14:06, 5F
→
03/16 15:23, , 6F
03/16 15:23, 6F
→
03/16 15:24, , 7F
03/16 15:24, 7F
→
03/16 22:28, , 8F
03/16 22:28, 8F
→
03/16 22:29, , 9F
03/16 22:29, 9F
→
03/16 22:30, , 10F
03/16 22:30, 10F
→
03/16 22:31, , 11F
03/16 22:31, 11F
→
03/16 22:32, , 12F
03/16 22:32, 12F
→
03/16 22:33, , 13F
03/16 22:33, 13F
推
03/16 23:03, , 14F
03/16 23:03, 14F
→
03/16 23:03, , 15F
03/16 23:03, 15F
推
03/18 22:06, , 16F
03/18 22:06, 16F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章