亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

工廠函數中的“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}, $)`;  };  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}, $)`;

  };

  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

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



查看完整回答
反對 回復 2023-07-20
?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

當您刪除時const { r, g, b } = this;,將引用您分配給的rgb(${r}, ${g}, $)參數。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}, $)`;

  };

  //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 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號