为了账号安全,请及时绑定邮箱和手机立即绑定

工厂函数中的“This”

工厂函数中的“This”

炎炎设计 2023-07-20 14:25:56
如果这是一个非常愚蠢的问题,我很抱歉。我对此进行了搜索,但找不到明确的答案。网上的教程中有一个工厂函数,如下所示。我基本上了解“ 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)
查看完整描述

3 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

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

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



查看完整回答
反对 回复 2023-07-20
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

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

当您调用 时makeColor,它会执行函数中的任何操作,然后返回一个值。在您的情况下,该值是color中定义的对象makeColor。如果去掉return就会返回undefined


查看完整回答
反对 回复 2023-07-20
?
温温酱

TA贡献1752条经验 获得超4个赞

即使我删除“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()



查看完整回答
反对 回复 2023-07-20
  • 3 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信