2017-11-17 56 views
1

在代碼審查,有人指出,我可以用傳播經營者和不斷更新的對象:爲什麼const通過spread運算符更新屬性?

const props = { 
 
    hairColor: 'brown', 
 
}; 
 

 
const hairColor = 'red'; 
 
const newProps = { ...props, hairColor}; 
 

 
console.log(newProps); // -> hairColor now equals 'red'

的問題是,如何工作的呢?

我理解實際上如何傳遞對象的工作原理:

const newProps = { ...props, { hairColor: 'red' }}; 

但它是如何知道更新hairColor與價值「紅」?一個快速測試顯示它使用變量名稱,但是如何?

const props = { 
 
    hairColor: 'brown', 
 
}; 
 

 
const colorOfHair = 'red'; 
 
const newProps = { ...props, colorOfHair}; 
 

 
// -> hairColor still equals 'brown' 
 
// with new property 'colorOfHair' 
 
console.log(newProps);

+0

這就是所謂的[速記屬性名稱(HTTPS ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015)。 –

回答

2

這是ES6 shorthand property names。當您在對象中編寫name時,它是name: name的快捷方式。所以

const newProps = { ...props, hairColor}; 

是短期的

const newProps = { ...props, hairColor: hairColor}; 

這是毫無關係的傳播經營者,同樣的事情發生,如果你寫:

const newProps = { prop1: 1, prop2: 2, hairColor }; 
相關問題