为什么需要在此函数中评估`this`关键字?

bab*_*gau 4 javascript this

任何人都可以帮我解释this关键字在此代码段中的作用.我正在阅读JS: The Definitive Guide并遇到这个问题:

// 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, "");
};
Run Code Online (Sandbox Code Playgroud)

Kha*_*lid 5

那么这个测试

if (!this) return this;
Run Code Online (Sandbox Code Playgroud)

表示如果字符串为空,则返回this,在这种情况下为空字符串.

如果删除此测试,该函数仍然有效,但保持它将使函数更快,因为您不必replace在字符串为空时调用该函数.

请注意,此测试if (!this) return this;不适用于null或者undefined值,因为它们内部没有函数来调用证明是我们不能这样做:

undefined.trim();
null.trim();
Run Code Online (Sandbox Code Playgroud)