创建原生的方法

首先一提到js创建原生的方法,我想到的是继承:prototype。
例如简单实现一个多次显示字符串的方法。

1
2
3
4
5
6
7
8
String.prototype.repe = function(times) {  
var str = '';
for (var i = 0; i < times; i++) {
str += this;
}
return str;
};
console.log('helloworld'.repe(5)); //helloworldhelloworldhelloworldhelloworldhelloworld

但这样其实有个问题,就是万一新创建的方法已经存在,那就会出现覆盖现象,要规避这个问题,一开始就要判断一下是否有该方法,因此,百度之后我发现可以这样:

1
2
3
4
5
6
7
8
String.prototype.repe = String.prototype.repe || function(times) {  
var str = '';
for (var i = 0; i < times; i++) {
str += this;
}
return str;
};
console.log('helloworld'.repe(5)); //helloworldhelloworldhelloworldhelloworldhelloworld

先判断这样就规避了出现覆盖的情况。

坚持原创技术分享,您的支持将鼓励我继续创作!