很抱歉,如果这是一个非常愚蠢的问题。我已经搜索过此内容,却找不到明确的答案。网络上的教程中有一个工厂功能,如下所示。我最了解“ 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)
答案 0 :(得分:0)
即使删除“ This”,代码仍然有效
我认为您是说它仍然可以在此行中被注释掉
//const { r, g, b } = this;
原因是您实际上对变量r
,g
和b
有一个封闭,因此您仍然可以读取它们。
我也不明白为什么要删除“返回颜色”;破坏“ color.rgb()”。
删除返回行会中断所有内容,因为现在您的makeColor
函数返回了undefined:
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
行返回具有属性r
,g
,b
和函数rgb()
答案 1 :(得分:0)
删除const { r, g, b } = this;
时,rgb(${r}, ${g}, ${b})
引用分配给makeColor
的{{1}}的参数。
调用color
时,它将执行函数中的所有操作,然后返回一个值。在您的情况下,该值为makeColor
中定义的color
对象。
如果删除退货,它将退回makeColor
答案 2 :(得分:0)
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
对于第二个问题,工厂方法是构建某些东西,然后通过从函数返回它来产生该东西。如果您不将其退回,它将保留在本地状态,并且完全没有用。