【问题标题】:Uncaught TypeError: Object [object DOMWindow] has no method 'replace'未捕获的类型错误:对象 [object DOMWindow] 没有“替换”方法
【发布时间】:2012-03-11 11:16:20
【问题描述】:

我正在学习 JavaScript。我只是想明白为什么下面代码中的strip2()函数不起作用,并返回错误。

<script type="text/javascript">
function strip1(str) {
  return str.replace(/^\s+|\s+$/g, "")
};
function strip2() {
  return this.replace(/^\s+|\s+$/g, "")
};

var text = ' Hello  ';
console.log(strip1(text));  // Hello
console.log(strip2(text));  // Uncaught TypeError: Object [object DOMWindow] has no method 'replace'
</script>

谢谢。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    this 在该上下文中是指向全局 window 对象的指针,该对象没有替换功能(因为它不是字符串)。因此,它会引发错误。

    【讨论】:

      【解决方案2】:

      正确的版本是:

      console.log(strip2.call(text));
      

      【讨论】:

        【解决方案3】:
        function strip2() {
          return arguments[0].replace(/^\s+|\s+$/g, "")
        };
        

        【讨论】:

          【解决方案4】:

          在 JavaScript 中,this 总是指我们正在执行的函数的“所有者”,或者更确切地说,指的是函数作为方法的对象。

          所以 strip2 正在全局 window 对象上调用 replace。

          作为参考,这是一篇解释 JavaScript 中 this 关键字的文章:http://www.quirksmode.org/js/this.html

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-01-08
            • 2013-04-19
            • 2012-12-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多