`
ArcTan
  • 浏览: 3750 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

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

阅读更多
本文翻译自【 Extending JavaScript – The Right Way

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.

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

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.

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

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

通常最简单的写法如下:

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:

它能正常工作,但如果像下面这样用:

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


We would get the output:

我们会得到下面的结果:

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.

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

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:

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

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.

现在再运行之前的迭代代码,便会得到我们想要的结果:

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:

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

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


        String.pxToInt()
        Convert css px value like “200px” to an Integer.
        将“200px”这样css格式的数值转成一个Integer
if(!String.prototype.pxToInt)
{
    Object.defineProperty(String.prototype, 'pxToInt',
    {
        value: function()
        {
            return parseInt(this.split('px')[0]);
        },
        enumerable: false
    });
}


        String.isHex()
        Checks if string is valid Hex value such as “#CCC” or “#CACACA”.
        验证字符串格式是否符合 HEX 颜色,形如 “#CCC” 或 “#CACACA”
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
    });
}


        String.reverse()
        Reverse a string.
        反转字符串
if(!String.prototype.reverse)
{
    Object.defineProperty(String.prototype, 'reverse',
    {
        value: function()
        {
            return this.split( '' ).reverse().join( '' );
        },
        enumerable: false
    });
}



        String.wordCount()
        Count the number of words in a given string, words being separated by spaces.
        统计给出字符串的英文单词数,通常英文单词都是用一个空格隔开的。
if(!String.prototype.wordCount)
{
    Object.defineProperty(String.prototype, 'wordCount',
    {
        value: function()
        {
            return this.split(' ').length;
        },
        enumerable: false
    });
}



        String.htmlEntities()
        Converts HTML characters like < and > to HTML encoded special characters.
        将字符串中的HTML字符转换成HTML实体
if(!String.prototype.htmlEntities)
{
    Object.defineProperty(String.prototype, 'htmlEntities',
    {
        value: function()
        {
            return String(this).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
        },
        enumerable: false
    });
}

此段代码被原作者发布文章的网页进行了错误的解释,下面给出正确的代码
if(!String.prototype.htmlEntities)
{
    Object.defineProperty(String.prototype, 'htmlEntities',
    {
        value: function()
        {
            return String(this).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        },
        enumerable: false
    });
}


        String.stripTags()
        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
    });
}



        String.trim()
        Removes all leading and trailing white space from string.
        去除所有头尾空格
if(!String.prototype.trim)
{
    Object.defineProperty(String.prototype, 'trim',
    {
        value: function()
        {
            return this.replace(/^\s*/, "").replace(/\s*$/, "");
        },
        enumerable: false
    });
}



        String.stripNonAlpha()
        Removes all non-alphanumeric characters from string.
        去除所有非字母字符
if(!String.prototype.stripNonAlpha)
{
    Object.defineProperty(String.prototype, 'stripNonAlpha',
    {
        value: function()
        {
            return this.replace(/[^A-Za-z ]+/g, "");
        },
        enumerable: false
    });
}



        String.sizeof()
        The the size of an object, for example: {one: “and”, two: “and”} would equal 2
        统计对象包含的成员数。例如:{one: “and”, two: “and”}的成员数为2
if(!Object.prototype.sizeof)
{
    Object.defineProperty(Object.prototype, 'sizeof',
    {
        value: function()
        {
            var counter = 0;
            for(index in this) counter++;
            
            return counter;
        },
        enumerable: false
    });
}
分享到:
评论

相关推荐

    扩展JavaScript功能的正确方法(译文)

    原文地址:Extending JavaScript – The Right Way以下是译文 JavaScript已经内置了很多强大的方法,但有时你需要的某个功能在内置的方法中没有,我们怎么来优雅地扩展JavaScript功能呢。 例如我们想增加一个...

    javascript常用工具集(带使用示例)

    * 从身份证号中得到生日和...* 正则表达式实现JavaScript日期格式化对Date的扩展,将 Date 转化为指定格式的String * 返回当天是星期几 * 常用正则表达式 * 将阿拉伯数字翻译成中文的大写数字 * 将日期转换成中文日期

    i18next是浏览器或任何其他JavaScript环境(例如node.js)的非常流行的国际化框架-javascript

    正确的复数形式 翻译上下文嵌套,变量替换 灵活性: 随处使用 可扩展性: 例如。 sprintf ... 如需更多信息,请访问网站:翻译功能 API 入门 我们的重点是为构建蓬勃发展的生态系统提供核心。 独立于您选择的构建...

    外文翻译 stus MVC

    The page designer (or HTML developer) must understand colors, the customer, product flow, page layout, browser compatibility, image creation, JavaScript, and more. Putting a great looking site ...

    yas.js:纯 Javascript + HTMLCSS 中的 y86 汇编器、虚拟机和可视化器

    该应用程序将显示您的代码、将其翻译成机器代码以及寄存器和堆栈图。 “高级”按钮允许您一次单步执行您的代码一条指令,并查看图表和输出更新。 注意:此应用程序使用高级 JavaScript。 需要现代浏览器才能获得...

    狮偶编程语言主工程 包含编辑器、编译和链接 js运行时

    狮偶编程语言主工程是一个...这个功能极大地扩展了狮偶编程语言的应用范围,使开发人员可以更轻松地与现有的JavaScript代码进行集成。总的来说,狮偶编程语言主工程是一个功能强大且易于使用软件套件,完整的开发环境

    magento-merchant-store-popup:在切换 B2CB2B 商店之前显示弹出窗口的 Magento 扩展

    您将需要自定义模板或至少在商店级别的翻译以显示正确的消息。要求PHP &gt;= 5.2.0 Mage_Core兼容性Magento &gt;= 1.4安装说明通过 Modman 或 Composer 安装扩展。 自定义模板和/或翻译。 清除缓存。卸载从 Magento 安装...

    laabr:格式良好,可扩展的pino记录器,用于hapi.js

    格式良好,可扩展的pino记录器,用于hapi.js oy! 奇迹般有效。 — 预设⇗ 例子开发与测试贡献 介绍laabr是用于hapi.js的格式良好的pino⇗记录器,它基于插件hapi-pino⇗ 。 它使您可以选择登录JSON,以便进行后处理...

    duolingo-solution-viewer:一个浏览器扩展程序,可以访问Duolingo上的翻译听力挑战的解决方案列表,并恢复听力挑战的错别字更正

    Duolingo解决方案查看器 一个浏览器扩展程序,可以访问针对的翻译/听力挑战的公认解决方案的完整列表,并恢复针对听力挑战的错别字的更正。目录错误报告和功能要求 下载Chrome扩展程序Firefox附加组件Opera插件 特征...

    Wicket 8.X开发文档(中文翻译+英文原版)

    使用wicket标记继承:扩展标记 5.5。摘要 6.保持对HTML的控制 6.1。隐藏或禁用组件 6.2。修改标签属性 6.3。生成标记属性“id” 6.4。使用WebMarkupContainer创建内嵌面板 6.5。使用标记片段 6.6。将标题内容添加到...

    asp.net知识库

    动态调用对象的属性和方法——性能和灵活性兼备的方法 消除由try/catch语句带来的warning 微软的应试题完整版(附答案) 一个时间转换的问题,顺便谈谈搜索技巧 .net中的正则表达式使用高级技巧 (一) C#静态成员和...

    大名鼎鼎SWFUpload- Flash+JS 上传

    SWFUpload v2 延续了SWFUpload的设计目标,将UI分离以交给开发人员控制和后续扩展 概述 传统的HTML上传 标准的HTML上传表单为用户提供一个文本框和按钮来选择文件,选中的文件是随着form表单提交的。整个文件上传...

    ExtAspNet_v2.3.2_dll

    -俄语翻译(feedback:vbelyaev)。 +2010-06-30 v2.3.1 -ExtAspNet控件将不在依赖ViewState,减少1/4左右的HTTP数据传输量。 -控件和示例的增强。 +2010-03-28 v2.2.1 +为TabStrip的GetAddTabReference...

    XML 讲解和分析

    XML 提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据。 目录 格式特性 简明语法 编辑本段格式特性  XML与Access,Oracle和SQL Server等数据库不同,数据库提供了更强有力的数据存储和分析能力,...

    okadibdjfemgnhjiembecghcbfknbfhg:增强版Steam — https

    正确计算套装折扣 显示在Steam上花费的总金额 突出显示您在游戏页面上拥有的DLC 在您的愿望清单中修复“无可用图像”游戏图标 和更多! 安装 自动的 单击并按照说明进行操作 (不起作用?尝试,然后单击“添加到...

    sailsjs-docs-gitbook:sails.js 官方文档 多语言电子书

    语言仅仅是交流信息、传情达意而已,更何况是技术文档,不掺杂任何感情色彩,因此中文翻译的标准仅仅是“覆盖全面、理解正确、表述清晰”,如果您感觉没有达到这一点,可以翻看对应英文原文(我写的+我想的=原文,^_...

    XML轻松学习手册--XML肯定是未来的发展趋势,不论是网页设计师还是网络程序员,都应该及时学习和了解

    DTD是一种保证XML文档格式正确的有效方法,可以比较XML文档和DTD文件来看文档是否符合规范,元素和标签使用是否正确。一个DTD文档包含:元素的定义规则,元素间关系的定义规则,元素可使用的属性,可使用的实体或...

    DotNetTextBox所见即所得编辑器控件 v3.3.1

    4) 使用帮助.CHM里的常见问题增加对应用全局样式后不能使用功能页面的解决方法。 5) 优化了控件部分户端代码。 6) 更新了部分多语言的翻译文字。 &lt;br&gt;2007/8/10 Version 3.2.8 Free &lt;br&gt;Updates:...

    java开源包1

    JSEditor 是 Eclipse 下编辑 JavaScript 源码的插件,提供语法高亮以及一些通用的面向对象方法。 Java数据库连接池 BoneCP BoneCP 是一个高性能的开源java数据库连接池实现库。它的设计初衷就是为了提高数据库连接...

    java开源包11

    JSEditor 是 Eclipse 下编辑 JavaScript 源码的插件,提供语法高亮以及一些通用的面向对象方法。 Java数据库连接池 BoneCP BoneCP 是一个高性能的开源java数据库连接池实现库。它的设计初衷就是为了提高数据库连接...

Global site tag (gtag.js) - Google Analytics