3 回答

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}, $)`;
};
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
對于第二個問題,工廠方法是構建一些東西,然后通過從函數返回它來生產該東西。如果您不歸還它,它將保持本地狀態并且根本沒有用處。

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

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}, $)`;
};
//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()
添加回答
舉報