首页 > 语言 > JavaScript > 正文

Prototype源码浅析 String部分(一)之有关indexOf优化

2024-05-06 14:22:36
字体:
来源:转载
供稿:网友

添加到String.prototype中的方法比较多,不过归结起来,大致分为下面几类:

分类方法名 
原始能力增强              strip |  include  |  startsWith  |  endsWith |  empty |  blank
格式camelize | capitalize |  underscore |  dasherize  | inspect          
变形toArray |  succ  | times
替换interpolate  | sub |  scan |  truncate | gsub
HTML处理stripTags  | escapeHTML |  unescapeHTML
参数序列化toQueryParams
JSON处理unfilterJSON |  isJSON |  evalJSON |  parseJSON
脚本处理stripScripts |  extractScripts  | evalScripts

从基本的原始能力增强开始,下面是具体的实现,这一段很好理解的:
代码如下:
(function(s){
function strip(){
return this.replace(/^/s+/,'').replace(//s+$/,'');
}
function include(pattern){
return this.indexOf(pattern) > -1;//split
}
function startsWith(pattern) {
return this.lastIndexOf(pattern, 0) === 0;
}
function endsWith(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.indexOf(pattern, d) === d;
}
function empty() {
return this == '';
}
function blank() {
return /^/s*$/.test(this);
}
s.strip = String.prototype.trim || strip;
s.include = include;
s.startsWith = startsWith;
s.endsWith = endsWith;
s.empty = empty;
s.blank = blank;
})(String.prototype);

上面的strip在jquery里面是$.trim,而且大部分貌似都是trim。这里直接扩展原生原型的悲剧之处就显现出来了,因为后面的JS实现中(比如chrome)就实现了trim方法,那就弄巧成拙了。
代码如下:
function strip(){
return this.replace(/^/s+/,'').replace(//s+$/,'');
}

这里面的replace(/^/s+/,'')就是trimLeft,replace(//s+$/,'')是trimRight,不过Prototype.String中没有这两个方法。

下面是这一部分比较有意思的地方:

当时看这段的时候,对其中的startsWith和endsWith甚是不解,按理来说,startsWith用indexOf就可以了,这里却是用的lastIndexOf。后来去翻了一下Prototype1.6版本的实现:
代码如下:
function startsWith(pattern) {
return this.indexOf(pattern) === 0;
}

function endsWith(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
}

可见,以前版本中startsWith用的就是indexOf,不过1.7版本修改了startsWith的实现。在1.7版本中:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选