有人能帮我解释一下这段代码中 this
关键字的作用吗?我正在阅读《JavaScript权威指南》,遇到了这个问题:
// 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, "");
};
trim
方法已经从String
类中扩展了,为什么我们需要再次评估它是否是一个String对象
呢? - babygau.trim()
方法的预期语义。你应该将其删除。“...权威指南”... 是啊,好吧。 - cookie monster