JavaScript 面向对象自定义MyString()的构造器函数,实现内建String()属性和方法:

js自定义MyString()构造器函数,实现内建String()属性和方法如下:

var s = new MyString('hello');
    s.length; //5
    s[0]; // "h"
    s.toString(); // "hello"
    s.valueOf();  // "hello"
    s.charAt(1); // "e"
    s.charAt('2'); // "l"
    s.charAt('e'); // "h"
    s.concat(' world!'); // "hello world!"
    s.slice(1, 3); // "el"
    s.slice(0, -1); // "hell"
    s.split('e'); // ["h", "llo"]
    s.split('l'); // ["h", "", "o"]
    s.split(); // ["hello"]
    s.reverse(); // "olleh"
 

function MyString(str) {
    var str = str.toString();
    var arr = [];
    for (var i in str) {
        this[i] = arr[i] = str[i];
    }
    this.length = arr.length;
    this['[[PrimitiveValue]]'] = str;
}
MyString.prototype.toString = function () {
    return this['[[PrimitiveValue]]']+'';
}
MyString.prototype.valueOf = function () {
    return this['[[PrimitiveValue]]'];
}
MyString.prototype.charAt = function (pos) {
    var pos = pos*1 || 0;
    return this[pos] || '';
}
MyString.prototype.concat = function (strings) {
    return this.toString()+strings;
}
MyString.prototype.slice = function (start,end) {
    var start = start>=0?start : this.length+start || 0; //-1
    var end   = end  >=0?end   : this.length+end || 0; //-1
        start = start <= this.length ? start:this.length;
        end   = end   <= this.length ? end:this.length;
    var str = '';
    for (var i = start; i<end; i++) {
        str+=this[i];
    }
    return str;
}
MyString.prototype.split = function (separator) {
    var arr = [];
    var index=0;
    for (var i=0; i<this.length; i++){
        if(this[i]==separator) {
            arr[arr.length] = this.slice(index,i);
            index = i+1;
        }
    }
    arr[arr.length] = this.slice(index,i);
    return arr;
}
// for循环版
MyString.prototype.reverse = function () {
    var str = '';
    for (var i = this.length-1; i>-1; i--) {
        str += this[i];
    }
    return str;
}
//借助数组的reverse()方法
MyString.prototype.reverse = function () {
    var arr = [];
    for (var i = 0; i<this.length; i++) {
        arr[arr.length] = this[i];
    }
    return arr.reverse().join('');
}

*版权声明:本文为原创文章,未经允许不得转载。

发布时间:2018-10-24
目录