3 回答

TA貢獻(xiàn)1854條經(jīng)驗 獲得超8個贊
const { r, g, b } = this;此行this引用創(chuàng)建的對象實例,如果刪除此行,它將起作用,因為函數(shù)方法中的參數(shù)名稱與構(gòu)造的對象的屬性名稱匹配。這就是代碼“有效”的原因。
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}, $)`;
};
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}, $)`;
};
return color;
}
const newColor2 = makeColor2(50, 100, 150);
newColor2.b = 0;
console.log(newColor2.rgb()); // b is 0 as expected
對于第二個問題,工廠方法是構(gòu)建一些東西,然后通過從函數(shù)返回它來生產(chǎn)該東西。如果您不歸還它,它將保持本地狀態(tài)并且根本沒有用處。

TA貢獻(xiàn)1906條經(jīng)驗 獲得超3個贊
當(dāng)您刪除時const { r, g, b } = this;
,將引用您分配給的rgb(${r}, ${g}, $)
參數(shù)。makeColor
color
當(dāng)您調(diào)用 時makeColor
,它會執(zhí)行函數(shù)中的任何操作,然后返回一個值。在您的情況下,該值是color
中定義的對象makeColor
。如果去掉return就會返回undefined

TA貢獻(xiàn)1752條經(jīng)驗 獲得超4個贊
即使我刪除“This”,代碼仍然有效
我想你的意思是,這條線注釋掉后它仍然有效
//const { r, g, b } = this;
原因是您本質(zhì)上對變量r、 、進(jìn)行了閉包g,b因此您仍然可以讀取它們。
我也不明白為什么要刪除“返回顏色;” 破壞“color.rgb()”。
刪除返回行會破壞一切,因為現(xiàn)在您的makeColor函數(shù)返回未定義:
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}, $)`;
};
//return color;
}
const newColor = makeColor(50, 100, 150);
//newColor.rgb();
console.log(newColor); // undefined
//console.log(newColor.rgb()); //rgb(50, 100, 150)
該行返回具有屬性、和函數(shù)return color
的對象r
g
b
rgb()
添加回答
舉報