我要實現的JavaScript字符串內置功能,但我有length屬性它是實現JavaScript字符串長度屬性的正確方法嗎?
下面有點困惑是我實現
function MyString(str){
this.str=str;
//properties
this.length=0;
if(typeof this.str[0]=='undefined')
this.length=0;
else
for (var i = 0; typeof this.str[i]!='undefined' ; i++)
this.length++;
//tostring method
this.toString=function(){
if(typeof this.str == 'string')
console.log(this.str);
else
console.log("cannot be converted to String") ;
}
}
這是貫徹落實長度property.Because它看起來可怕的正確方法對我來說,或者如果我想計算長度只有當用戶調用'str.length'和仍然長度應該保留作爲財產,我該怎麼做
我做了一個替代就是這樣,但會是功能
this.length=function(this.str){
//length logic here
}
我如何能實現它在一個更好的辦法,但仍然長度似乎是一個財產
的問題是 「爲什麼?」 [str.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length)將返回字符串的長度 – mplungjan 2015-02-23 12:56:04
這就是我的問題。 – Andy 2015-02-23 12:56:36
你正在重塑車輪 – 2015-02-23 13:02:40