用替换失去上下文

losing context with replace

在 QooxDoo 中,这段代码有问题

html2plain : function (html) {
     html = html.replace(/<(S*?)[^>]*>.*?|<.*?\/>/g,  function( tag )
     {
          return this.pushHashtag(tag.toUpperCase());
      } );
      return( html );
 },

说到行

return this.pushHashtag(tag.toUpperCase());

变量 this 没有上下文,函数 pushHashtag 变得不可用。

解决这个问题的一种方法是将 'this' 绑定到函数。 为此,您需要按如下方式更改匿名函数(您应该将此函数发送到 replace 方法):

function(tag) {
  return this.pushHashtag(tag.toUpperCase());
}.bind(this)

现在,在这个函数中,'this' 将引用 "right" 'this'