作为一个前端,首先要必须搞懂JS的prototype、__proto__与constructor属性,本文主要讲prototype,通过prototype属性给对象的构造函数添加新的属性。
举个栗子:
function Person () {
this.age = '20';
}
var person = new Person();
// person['name'] = 'test';
Person.prototype.sex = '男';
Person.prototype.name = 'test';
console.log(person.name)
console.log(person)
从上面的代码执行结果可以看出通过使用 prototype 属性就可以给对象的构造函数添加新的属性。
当然我们也可以使用 prototype 属性就可以给对象的构造函数添加新的方法。
接着上面的例子
function Person () {
this.age = '20';
}
var person = new Person();
// person['name'] = 'test';
Person.prototype.sex = '男';
Person.prototype.name = 'test';
Person.prototype.test = function() {
console.log('hello word');
}
person.say();
输出'hello word',那么同理也可以使用 prototype 属性自定义新的方法。
重点来了
String.prototype.replaceStr = function(oldChar, newChar) {
//得到出现字符串时的下标
var fromIndex = this.indexOf(oldChar);
if (fromIndex == -1) return this.toString();
//前段字符串
var firstStr = this.substring(0, fromIndex);
//后段字符串
var nextStr = this.substring(fromIndex + oldChar.length, this.length);
return firstStr + newChar + nextStr;
}
var teststr ="asdfasd";
console.log(teststr.replaceStr("as","www"));
输出结果可以看出字符串中首次出现的'as'已经替换成了'www',这时候我们重写js的replace函数的功能已经实现了,后面还有一个'as'还未替换,怎么办勒?继续往下看
String.prototype.replaceAll = function(s1,s2){
//g 执行全局匹配 m 执行多行匹配
return this.replaceStr(new RegExp(s1,"gm"),s2);
}
var teststr ="asdfasd";
console.log(teststr.replaceAll("as","www"));
输出的结果果然把字符串中所有的'as'替换成功了。
当然了也可以这样写,例如:
String.prototype.replaceAll = function(oldstr, newstr) {
var oldlength = this.length;
//调用上面自定义的替换方法
var ret = this.replaceStr(oldstr, newstr);
while(this.indexOf(oldstr) != -1) {
return ret.replaceAll(oldstr, newstr);
}
return ret;
}
var teststr ="asdfasd";
console.log(teststr.replaceAll("as","www"));