gpt4 book ai didi

javascript - 为什么需要在这个函数内部评估 `this` 关键字?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:46:16 25 4
gpt4 key购买 nike

谁能帮我解释一下 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, "");
};

最佳答案

这个测试好了

if (!this) return this;

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

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

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

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

关于javascript - 为什么需要在这个函数内部评估 `this` 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com