As a front end, we must first understand JS prototype, __proto__ and constructor properties. This article focuses on prototype, using the Prototype property to add new properties to the object constructor.

Here’s an example:

function Person () {
    this.age = '20';
}
var person = new Person();
// person['name'] = 'test';
Person.prototype.sex = 'male';
Person.prototype.name = 'test';
console.log(person.name)
console.log(person)
Copy the code
As you can see from the code execution above, you can add new properties to the object’s constructor by using the Prototype property.
We can also use the Prototype property to add new methods to the object’s constructor.

Follow the example above

function Person () {
    this.age = '20';
}
var person = new Person();
// person['name'] = 'test';
Person.prototype.sex = 'male';
Person.prototype.name = 'test';
Person.prototype.test = function() {
    console.log('hello word');
}
person.say();
Copy the code
Output ‘Hello word’, and you can use the Prototype property to customize the new method as well.

The key to the

String.prototype.replaceStr = function(oldChar, newChar) {var fromIndex = this.indexof (oldChar);if (fromIndex == -1) returnthis.toString(); Var firstStr = this.substring(0, fromIndex); 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"));
Copy the code
Replace (‘ WWW ‘, ‘as’); replace (‘ WWW ‘, ‘as’); Keep reading
String.prototype.replaceAll  = function(s1,s2){//g performs global matching. M performs multi-line matchingreturn this.replaceStr(new RegExp(s1,"gm"),s2);     
} 
var teststr ="asdfasd"; 
console.log(teststr.replaceAll("as"."www"));
Copy the code
As expected, the output succeeded in replacing all ‘as’ in the string.

You can also write this, for example:

String.prototype.replaceAll = function(oldstr, newstr) { var oldlength = this.length; Var ret = this.replacestr (oldstr, newstr); 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"));
Copy the code
The output is the same, then….. Didn’t!