Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Object [object DOMWindow] has no method 'replace'

Tags:

javascript

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.

like image 949
kinakomochi Avatar asked Feb 22 '23 04:02

kinakomochi


1 Answers

this 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.

like image 183
Waynn Lue Avatar answered May 01 '23 15:05

Waynn Lue