javascript - 无法在 jsfiddle 中执行 Doug Crockford 的 deentityify 示例

标签 javascript

我正在尝试使用 jsfiddle 执行 Douglas Crockfords J-TBP 书中那个非常好的 deentityify 示例

String.method('deentityify', function() {
    // The entity table. It maps entity names to
    // characters.
    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };
    // Return the deentityify method.
    return function() {
        // This is the deentityify method. It calls the string
        // replace method, looking for substrings that start
        // with '&' and end with ';'. If the characters in
        // between are in the entity table, then replace the
        // entity with the character from the table. It uses
        // a regular expression (Chapter 7).
        return this.replace(/&([^&;]+);/g, function(a, b) {
            var r = entity[b];
            return typeof r === 'string' ? r : a;
        });
    };
}());

document.writeln('&lt;&quot;&gt;'.deentityify()); // <">          

最佳答案

此代码片段依赖于一些糖,即 method 方法,您必须事先定义它。 (它在本书的前面描述过。)它的在线副本和解释在 the "Sugar" section of Crockford's article "Classical Inheritance in JavaScript" 中。 .它看起来像这样:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

您的 Fiddle 的更正版本包含以上内容,位于 http://jsfiddle.net/W9Ncd/。 .

关于javascript - 无法在 jsfiddle 中执行 Doug Crockford 的 deentityify 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405010/

相关文章:

javascript - 如何监听 Ace Editor 更改事件并使用react

javascript - NgOnChanges 在用户键入时覆盖表单控件值

javascript - 在 coffeescript 中编写 jquery 插件 - 如何获取 "(function($)"和 "(jQuery)"?

javascript - jquery/ajax 的意外结果

javascript - 使用 Javascript 隐藏 Href 链接

javascript - 用于 jquery 布局的自定义切换器

javascript - 如何从 javascript 中的项目列表创建字典列表?

javascript - 迭代 map 标记

javascript - '@@DEBUG'在javascript中是什么意思?

javascript - 在可订阅函数中访问计算值