Uncaught TypeError: Object [object DOMWindow] does not have a 'replace' method

I am learning javascript. I just want to understand why the strip2 () function in the code below does not 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.

+4
source share
4 answers

this in this context is a pointer to a global window object that does not have a replace function (since it is not a string). Thus, it throws an error.

+4
source

The correct version is:

 console.log(strip2.call(text)); 
+2
source
 function strip2() { return arguments[0].replace(/^\s+|\s+$/g, "") }; 
+1
source

In JavaScript, this always refers to the "owner" of the function that we are executing, or rather, to the object in which the function is a method.

So strip2 causes a replacement on the global window object.

For reference, this is an article explaining the this in JavaScript: http://www.quirksmode.org/js/this.html

+1
source

Source: https://habr.com/ru/post/1400817/


All Articles