任何人都可以帮助我解释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, "");
};
答案 0 :(得分:5)
这个测试
if (!this) return this;
表示如果字符串为空,则返回this
,在这种情况下为空字符串。
如果删除此测试,该功能仍然有效,但保留该功能会使功能更快,因为当字符串为空时,您不必调用replace
函数。
请注意,if (!this) return this;
或null
值的此测试undefined
不是因为他们内部没有函数可以调用证明我们可以& #39; t就这样做:
undefined.trim();
null.trim();
答案 1 :(得分:-1)
如果this
为undefined
或null
,则最有可能用作错误检测。
if (!string.trim()) { alert("string is null or undefined."); }