工厂函数中的“This”

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


炎炎设计
浏览 93回答 3
3回答

哔哔one

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对于第二个问题,工厂方法是构建一些东西,然后通过从函数返回它来生产该东西。如果您不归还它,它将保持本地状态并且根本没有用处。

一只名叫tom的猫

当您删除时const { r, g, b } = this;,将引用您分配给的rgb(${r}, ${g}, ${b})参数。makeColorcolor当您调用 时makeColor,它会执行函数中的任何操作,然后返回一个值。在您的情况下,该值是color中定义的对象makeColor。如果去掉return就会返回undefined

温温酱

即使我删除“This”,代码仍然有效我想你的意思是,这条线注释掉后它仍然有效//const { r, g, b } = this;原因是您本质上对变量r、 、进行了闭包g,b因此您仍然可以读取它们。我也不明白为什么要删除“返回颜色;” 破坏“color.rgb()”。删除返回行会破坏一切,因为现在您的makeColor函数返回未定义: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的对象rgbrgb()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript