# 章序号/节序号/节/笔记序号 - Objective: # 概念阐释 ## 语义 `set`语法将**设置**对象中的属性,将属性绑定到对应的方法函数中。还可以在[[JavaScript Class类]]中使用。需要重新赋值的属性才需要用set。set可以随意更改属性值,所以不想让随意更改的属性不要用set。 ## 语法 ```js { set prop(val) { /* … */ } } ``` - `prop`:要绑定到给定函数的属性名。 - `val`:用于保存尝试分配给`prop`的值的参数。 # 举例子 ![](http://image.harryrou.wiki/2023-04-03-CleanShot%202023-04-03%20at%2008.48.36%402x.png) ```js const person = {   _age: 37,   set age(newAge){     if (typeof newAge === 'number'){       this._age = newAge;     } else {       console.log('You must assign a number to age');     }   } }; //通过新的「参数」newAge重新分配对象属性的值。调用setter method不需要(),更像是被重新赋值 person.age = 40; console.log(person._age); // 属性值37变为了40 person.age = '40'; // 不能更改属性的数据类型 //不需要通过set medthod就可以重新分配属性值 person._age = 'forty-five' console.log(person._age); // Prints forty-five ``` # 类比、比较与对比 [[js class 练习题 - 建立图书馆]] <table> <tr> <th></th> <th>this</th> <th>getter</th> <th>setter</th> <th>for...in loop</th> </tr> <tr> <th>作用</th> <td>在对象方法中引用属性</td> <td>在对象方法中读取属性</td> <td>在对象方法中给属性分配新的属性值,但不能改变数据类型</td> <td>创建一个变量来access属性并且遍历属性</td> </tr> <tr> <th>调用</th> <td>有括号</td> <td>无括号</td> <td>无括号</td> </tr> <tr> <th>函数参数</th> <td>无参数</td> <td>无参数</td> <td>新的变量为参数</td> </tr> <tr> <th>添加条件</th> <td>无条件</td> <td>可添加条件</td> <td>可添加条件</td> </tr> </table> # 问题 - [练习题](https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/setters) 添加一个setter方法使`numOfSensors`可以添加或删除sensors。 1. 添加一个名为`numOfSensors`的setter方法,使用`set`关键字。提供一个名为`num`的参数。 2. 添加一个条件,检查num是否为数字数据类型,并且这个数字需要大于等于0,如果符合,重新赋值`this._numOfSensors`为num。如果不符合,log`'Pass in a number that is greater than or equal to 0'` 3. 对象写好了,现在利用set方法改变`_numOfSensors`属性为100 4. 访问`_numOfsensors`看结果是否为100 # 问题答案 #### 错误集 - `this._numOfSensors = num` 不能颠倒写 - 调用`set`时重新赋值 - 在用this引用_属性时,如果数据类型写错,返回结果也不会报错,所以在使用`set`时要先用if条件确认数据类型 ```js const robot = { _model: '1E78V2', _energyLevel: 100, _numOfSensors: 15, get numOfSensors(){ if(typeof this._numOfSensors === 'number'){ return this._numOfSensors; } else { return 'Sensors are currently down.' } }, // code set numOfSensors (num) { if(typeof num === 'number' && num >= 0 ){ return this._numOfSensors = num; }else{ 'Pass in a number that is greater than or equal to 0' } } }; robot.numOfSensors = 100; console.log(robot) ``` # 备注(经验集/错误集) ## summary ## 参考资料