我正在学习 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>
谢谢。
最佳答案
this
在该上下文中是指向全局 window
对象的指针,它没有替换函数(因为它不是字符串)。因此,它会引发错误。
关于javascript - 未捕获的类型错误 : Object [object DOMWindow] has no method 'replace' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9654450/