"This" 在工厂函数中

"This" in Factory Functions

如果这是一个非常愚蠢的问题,我很抱歉。我已经搜索过了,找不到明确的答案。网络上的教程中有一个工厂函数,如下所示。我基本上了解“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)

The code still works even when I remove "This"

我假设你的意思是它仍然适用于注释掉的这一行

//const { r, g, b } = this;

原因是您基本上对变量 rgb 进行了闭包,因此您仍然可以读取它们。

I also don't understand why removing "return color;" breaks "color.rgb()".

删除 return 换行符 所有内容 现在您的 makeColor 函数 return 未定义:

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); // undefined
//console.log(newColor.rgb()); //rgb(50, 100, 150)

return color return 是具有属性 rgb 和函数 rgb()[=23 的对象=]

当您删除 const { r, g, b } = this; 时,rgb(${r}, ${g}, ${b}) 引用您分配给 colormakeColor 的参数。

当您调用 makeColor 时,它会执行函数中的任何操作,然后 return 一个值。在您的例子中,该值是 makeColor 中定义的 color 对象。 如果您删除 return,它将 return undefined

const { r, g, b } = this; 在这一行 this 中引用创建的对象实例,如果你删除这一行它将起作用,因为你的函数方法中的参数名称与构造对象的 属性 名称匹配.这就是代码“有效”的原因。

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: ƒ}
newColor.b = 0;
console.log(newColor.rgb()); // this still prints 150 where it should print 0
// cause b refers to the argument passed into the makeColor function not instance member 

function makeColor2(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 newColor2 = makeColor2(50, 100, 150);
newColor2.b = 0;
console.log(newColor2.rgb()); // b is 0 as expected

对于第二个问题,工厂方法是构建一些东西,然后通过 return 从函数中生成它。如果您不 return 它,它将保留在本地并且根本没有用。