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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With