扩展JavaScript的正确方法(翻译)

本文翻译自【 [url=http://www.websanova.com/tutorials/javascript/extending-javascript-the-right-way]Extending JavaScript – The Right Way[/url] 】

JavaScript comes with a lot of great functionality built in, but what if there is a function you need which is missing. How can we build them in seaminglessly in an elegant way that extends the functionality of our beloved JavaScript. The following will outline a couple methods to extend the existing functionality of JavaScript, both effective but one a little more functionally complete.

[color=blue]JavaScript 内建了很多很棒的函数,但也漏掉了一些我们很需要的,因此需要我们自己扩展。但如何才能将扩展的代码与亲爱的JavaScript优雅的融合在一起呢?接下来将向你展示几个小函数,扩展了已有的功能,让JavaScript更完整一点儿。[/color]

Say we want to create a function .capitalize() to extend the String type of JavaScript so that it behaves in a way similar to String.toLowerCase() or String.toUpperCase(). We can do this by prototyping the String object adding in our new function.

[color=blue]首先我们要为String类型扩展一个.capitalize()函数,它使用起来类似 String.toLowerCase() 或 String.toUpperCase() ,可以返回一个新的,被格式化为首字母大写,其他全部小写的字符串。我们可以用操作对象原型 prototype 的方式添加我们的新函数[/color]

This is usually done in the simplest way with the code below:

[color=blue]通常最简单的写法如下:[/color]


if(!String.prototype.capitalize)
{
String.prototype.capitalize = function()
{
return this.slice(0,1).toUpperCase() + this.slice(1).toLowerCase();
}
}


This works fine and dandy but lets say we were to do the following:

[color=blue]它能正常工作,但如果像下面这样用:[/color]


var strings = "yay";
for(i in strings) console.log(i + ":" + strings[i]);


We would get the output:

[color=blue]我们会得到下面的结果:[/color]


0: y
1: a
2: y
capitalize: function () { return this.slice(0, 1).toUpperCase() + this.slice(1).toLowerCase(); }


Our capitalize function shows up in our for loop, which is correct since it is now a property of all strings. The reason it is doing this is because the enumerable property for our new function is by default set to true.

[color=blue]我们的 capitalize 函数也出现在了循环中,并且作为一个属性出现在所有String对象中。造成此结果的原因是,我们新增加的函数,会被做上一个标记,它是通过设置改函数的 enumerable 属性为 true 来实现的,而通过这样的方式新增的函数默认就会将 enumerable 属性为 true 。[/color]

However, this was wreaking havoc on a plugin I had written that happened to be iterating through each character in a string. By simply changing the enumerable property to false we can avoid this problem which can be done by using the defineProperty method like so:

[color=blue]虽然在做String迭代操作时,我们书写的这个插件会造成严重的不良影响,但也不用如此担心。只要稍加修改,使用 defineProperty 函数来设置新增函数的 enumerable 值为 false,就可以解决这个问题,像下面这样:[/color]


if(!String.prototype.capitalize)
{
Object.defineProperty(String.prototype, 'capitalize',
{
value: function()
{
return this.slice(0,1).toUpperCase() + this.slice(1).toLowerCase();
},
enumerable: false
});
}


Now when we run our loop we get the outcome we were more likely expecting.

[color=blue]现在再运行之前的迭代代码,便会得到我们想要的结果:[/color]


var strings = "yay";
for(i in strings) console.log(i + ":" + strings[i]);


0: y
1: a
2: y


The reason for this may not seem as obvious when we’re looking at strings, but it gives us a lot of flexibility should we need it. It can come in really handy when defining our own objects and setting some default values that we would want to expose.

Below are just a few more examples you may wish to use in some of your own projects:

[color=blue]因为这个特性,字符串看上去并没有明显的变化,但却带来了很多我们需要的灵活性。借此,在实际应用中,我们可以方便的定义定义或设置我们自己的对象,使我们定义的方法可以按我们想要的方式展现给外界

下面是一些其他小函数的代码,这些例子可能也是你在项目中想要的。[/color]

[b]String.pxToInt()[/b]
Convert css px value like “200px” to an Integer.
[color=blue]将“200px”这样css格式的数值转成一个Integer[/color]

if(!String.prototype.pxToInt)
{
Object.defineProperty(String.prototype, 'pxToInt',
{
value: function()
{
return parseInt(this.split('px')[0]);
},
enumerable: false
});
}


[b]String.isHex()[/b]
Checks if string is valid Hex value such as “#CCC” or “#CACACA”.
[color=blue]验证字符串格式是否符合 HEX 颜色,形如 “#CCC” 或 “#CACACA”[/color]

if(!String.prototype.isHex)
{
Object.defineProperty(String.prototype, 'isHex',
{
value: function()
{
return this.substring(0,1) == '#' &&
(this.length == 4 || this.length == 7) &&
/^[0-9a-fA-F]+$/.test(this.slice(1));
},
enumerable: false
});
}


[b]String.reverse()[/b]
Reverse a string.
[color=blue]反转字符串[/color]

if(!String.prototype.reverse)
{
Object.defineProperty(String.prototype, 'reverse',
{
value: function()
{
return this.split( '' ).reverse().join( '' );
},
enumerable: false
});
}



[b]String.wordCount()[/b]
Count the number of words in a given string, words being separated by spaces.
[color=blue]统计给出字符串的英文单词数,通常英文单词都是用一个空格隔开的。[/color]

if(!String.prototype.wordCount)
{
Object.defineProperty(String.prototype, 'wordCount',
{
value: function()
{
return this.split(' ').length;
},
enumerable: false
});
}



[b]String.htmlEntities()[/b]
Converts HTML characters like < and > to HTML encoded special characters.
[color=blue]将字符串中的HTML字符转换成HTML实体[/color]

if(!String.prototype.htmlEntities)
{
Object.defineProperty(String.prototype, 'htmlEntities',
{
value: function()
{
return String(this).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
},
enumerable: false
});
}

[color=red]此段代码被原作者发布文章的网页进行了错误的解释,下面给出正确的代码[/color]

if(!String.prototype.htmlEntities)
{
Object.defineProperty(String.prototype, 'htmlEntities',
{
value: function()
{
return String(this).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
enumerable: false
});
}


[b]String.stripTags()[/b]
Strips out all HTML tags from the string.

if(!String.prototype.stripTags)
{
Object.defineProperty(String.prototype, 'stripTags',
{
value: function()
{
return this.replace(/<\/?[^>]+>/gi, '');
},
enumerable: false
});
}



[b]String.trim()[/b]
Removes all leading and trailing white space from string.
[color=blue]去除所有头尾空格[/color]

if(!String.prototype.trim)
{
Object.defineProperty(String.prototype, 'trim',
{
value: function()
{
return this.replace(/^\s*/, "").replace(/\s*$/, "");
},
enumerable: false
});
}



[b]String.stripNonAlpha()[/b]
Removes all non-alphanumeric characters from string.
[color=blue]去除所有非字母字符[/color]

if(!String.prototype.stripNonAlpha)
{
Object.defineProperty(String.prototype, 'stripNonAlpha',
{
value: function()
{
return this.replace(/[^A-Za-z ]+/g, "");
},
enumerable: false
});
}



[b]String.sizeof()[/b]
The the size of an object, for example: {one: “and”, two: “and”} would equal 2
[color=blue]统计对象包含的成员数。例如:{one: “and”, two: “and”}的成员数为2[/color]

if(!Object.prototype.sizeof)
{
Object.defineProperty(Object.prototype, 'sizeof',
{
value: function()
{
var counter = 0;
for(index in this) counter++;

return counter;
},
enumerable: false
});
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值