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

时间:2014-08-18 01:21:13

标签: 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, "");
};

2 个答案:

答案 0 :(得分:5)

这个测试

if (!this) return this;

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

如果删除此测试,该功能仍然有效,但保留该功能会使功能更快,因为当字符串为空时,您不必调用replace函数。

请注意,if (!this) return this;null值的此测试undefined不是因为他们内部没有函数可以调用证明我们可以& #39; t就这样做:

undefined.trim();
null.trim();

答案 1 :(得分:-1)

如果thisundefinednull,则最有可能用作错误检测。

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