4

Douglas Crockfords J-TBP book using jsfiddle で本当に素晴らしい 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()); // <">          
  • http://jsfiddle.net/cspeter8/7Pjzs/2/を参照してください- 動作しません! 結果ペインに '<">' が表示されるはずですが、何も表示されません。謎を解きたい人はいますか?
4

1 に答える 1

8

methodこのコード スニペットは、事前に定義しなければならないちょっとした砂糖、つまりメソッドに依存しています。(本書の早い段階で説明されています。) オンライン コピーとその説明は、Crockford の記事「JavaScript における古典的継承」の「シュガー」セクションにあります。次のようになります。

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

上記を組み込んだ Fiddle の修正版はhttp://jsfiddle.net/W9Ncd/にあります。

于 2012-11-15T19:52:23.310 に答える