admin管理员组文章数量:1323342
I'm studying javascript. I just want to understand why the strip2() function in the below code doesn't work, and returns an error.
<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>
Thanks.
I'm studying javascript. I just want to understand why the strip2() function in the below code doesn't work, and returns an error.
<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>
Thanks.
Share Improve this question edited Mar 11, 2012 at 11:30 Waynn Lue 11.4k8 gold badges52 silver badges77 bronze badges asked Mar 11, 2012 at 11:16 kinakomochikinakomochi 4854 gold badges8 silver badges15 bronze badges4 Answers
Reset to default 4this
in that context is a pointer to the global window
object, which doesn't have a replace function (since it isn't a string). So as a result, it throws an error.
The correct version would be:
console.log(strip2.call(text));
function strip2() {
return arguments[0].replace(/^\s+|\s+$/g, "")
};
In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.
So strip2 is calling replace on the global window
object.
For reference, this is an article explaining the this
keyword in JavaScript: http://www.quirksmode/js/this.html
本文标签: javascriptUncaught TypeError Object object DOMWindow has no method 39replace39Stack Overflow
版权声明:本文标题:javascript - Uncaught TypeError: Object [object DOMWindow] has no method 'replace' - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742133885a2422284.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论