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 badges
Add a ment  | 

4 Answers 4

Reset to default 4

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.

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