【发布时间】:2020-11-09 12:59:13
【问题描述】:
如果这是一个非常愚蠢的问题,我很抱歉。我已经搜索过它并找不到明确的答案。网络上的教程中有一个工厂函数,如下所示。我主要了解“This”如何在其他地方工作,但我不能完全理解“This”如何在这里帮助我们。即使我删除“This”,该代码仍然有效。我也不明白为什么删除“return color;”会破坏“color.rgb()”。
function makeColor(r, g, b) {
const color = {};
color.r = r;
color.g = g;
color.b = b;
color.rgb = function () {
//const { r, g, b } = this;
return `rgb(${r}, ${g}, ${b})`;
};
return color;
}
const newColor = makeColor(50, 100, 150);
newColor.rgb();
console.log(newColor); // {r: 50, g: 100, b: 150, rgb: ƒ}
console.log(newColor.rgb()); //rgb(50, 100, 150)
【问题讨论】:
-
r,g,b被构造函数中的变量封闭。在newColor.rgb()之前尝试newColor.r = 0,看看使用this和不使用this之间的区别。 -
如果你删除
return color,那么你的makeColor函数不会返回任何东西,所以变量newColor将是未定义的,因此newColor.rgb()不会做任何事情 -
非常感谢你们俩! @deceze 您的评论现在让我非常清楚范围将如何在这里工作!
-
@TKoL 我现在明白为什么不返回任何内容会破坏代码。
-
这能回答你的问题吗? How does the "this" keyword work?
标签: javascript function oop this factory