Why should this this keyword have to be evaluated inside this function?

Can someone help me explain the role of the keyword thisin this snippet. I read JS: The Definitive Guideand click on this:

// Define the ES5 String.trim() method if one does not already exist.
// This method returns a string with whitespace removed from the start and end.
String.prototype.trim = String.prototype.trim || function() 
{
   if (!this) 
    return this; // WHY EVALUATE `this` IN THIS FUNCTION???

    return this.replace(/^\s+|\s+$/g, "");
};
+4
source share
2 answers

Ok this test

if (!this) return this;

means if the string is empty, so it returns this, which in this case is an empty string.

if you delete this test, the function still works, but saving it will speed up the function because you do not need to call the function replacewhen the line is empty.

, if (!this) return this; null undefined, , , :

undefined.trim();
null.trim();
+5

, this - undefined null, .

if (!string.trim()) { alert("string is null or undefined."); }
-1

All Articles