# 章序号/节序号/节/笔记序号
# 概念阐释
## 语义
将对象作为函数的参数,在函数中对对象内容进行修改或增加。
## 语法
```js
const spaceship = {
homePlanet : 'Earth',
color : 'silver'
};
let paintIt = obj => {
obj.color = 'glorious gold'
};
paintIt(spaceship); //要先调用,直接console.log(paintIt(spaceship));否则会报错
spaceship.color // Returns 'glorious gold'
```
- `obj`是对象参数
- `obj.color` 访问对象属性
- `paintIt(spaceship); ` 调用spaceship对象
- 永远改变了原始对象中的颜色
# 举例子
## 反例
```js
let spaceship = {
homePlanet : 'Earth',
color : 'red'
};
let tryReassignment = obj => {
obj = {
identified : false,
'transport type' : 'flying'
}
console.log(obj) // Prints {'identified': false, 'transport type': 'flying'} 相当于重新创建了一个对象
};
tryReassignment(spaceship) // The attempt at reassignment does not work.
spaceship // Still returns {homePlanet : 'Earth', color : 'red'};
spaceship = {
identified : false,
'transport type': 'flying'
}; // Regular reassignment still works.重新赋值变量是有用的
```
在函数中,您可以**重新为对象分配属性**,但如果您尝试为**整个对象分配一个新值**,那么原始对象的引用将不会被更改。这是因为重新分配一个**新对象会创建一个新的引用**,而原始对象在函数外部仍然保持不变。
# 类比、比较与对比
# 问题
- [练习题](https://www.codecademy.com/courses/introduction-to-javascript/lessons/objects/exercises/pass-by-reference)
1. 添加一个`greenEnergy`函数,修改`spaceship`对象中的`'Fuel Type'`值为`'avocado oil'`;
2. 添加一个`remotelyDisable`函数,在`spaceship`对象中增加`disabled`为`true`的属性;
3. 调用2个函数,并print修改和增加后的结果。
# 问题答案
```js
let spaceship = {
'Fuel Type' : 'Turbo Fuel',
homePlanet : 'Earth'
};
let greenEnergy = (obj) => {
return obj['Fuel Type'] = 'avocado oil';
};
greenEnergy(spaceship);
console.log(spaceship);
let remotelyDisable = (obj) => {
return obj.disabled = true;
};
remotelyDisable(spaceship);
console.log(spaceship);
```
# 备注(经验集/错误集)
<div class="slideshow-container">
<div class="mySlides fade">
<div class="numbertext">1</div>
<img src="http://image.harryrou.wiki/2023-04-02-IMG_2103.jpeg" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
## 参考资料