在TGP中引入的模块模式deentityify方法 - 为什么这种模式是必要的? [英] Javascript module pattern introduced in TGP deentityify method - why is this pattern necessary?

查看:329
本文介绍了在TGP中引入的模块模式deentityify方法 - 为什么这种模式是必要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Crockford在deentityify方法中引入了一个模式来创建一个模块。他声称:

Crockford introduces a pattern in the deentityify method to create a module. He claims:


模块模式利用函数范围和关闭来创建绑定和私有的关系。在这个例子中,只有deentityify方法可以访问实体数据结构。

The module pattern takes advantage of function scope and close to create relationships that are binding and private. In this example, only the deentityify method has access to the entity data structure.

想要删除他的自定义函数,可以归结到...

Distilling to remove his custom functions, I think the code boils down to...

String.prototype.deentityify = function() {
    var entity = { 
        quot: '"',
        lt: '<',
        gt: '>'
    };

    return function() {
        return this.replace(/&([^&;]+);/g, function(a, b) {
            var r = entity[b];
            return typeof r === 'string' ? r : a;
        });  //close function(a,b)
    }; //close the returned function
} /* close  top level */ (); /* but evaluate it so deentitify becomes the returned fcn(!)

String.prototype.deentityify = function() {
    var entity = { 
        quot: '"',
        lt: '<',
        gt: '>'
    };

//    return function() {
        return this.replace(/&([^&;]+);/g, function(a, b) {
            var r = entity[b];
            return typeof r === 'string' ? r : a;
        });  //close function(a,b)
//    }; //close the returned function
} /* close  top level, don't evaluate


推荐答案

此模式的基本原因是避免在每次调用时重新评估实体。将实体替换为构建起来很昂贵,并且不会从调用更改为:

The basic reason for this pattern is to avoid re-evaluating entity on every call. Replace entity with something that is expensive to construct and doesn't change from call to call:

String.prototype.deentityify = function() {
    // expensiveFunctionCall is called *once* - when the function is defined.
    var entity = expensiveFunctionCall();

    return function() {
        return this.replace(/&([^&;]+);/g, function(a, b) {
            var r = entity[b];
            return typeof r === 'string' ? r : a;
        });  //close function(a,b)
    }; //close the returned function
}();

vs

String.prototype.deentityify = function() {
    // expensiveFunctionCall is called
    // *every time* "anyString".deentityify() is called.
    var entity = expensiveFunctionCall();

    return this.replace(/&([^&;]+);/g, function(a, b) {
        var r = entity[b];
        return typeof r === 'string' ? r : a;
    });  //close function(a,b)
};

这篇关于在TGP中引入的模块模式deentityify方法 - 为什么这种模式是必要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆