Javascript (advanced object)
Advanced Object
1. Arrow Function :
- Arrow function 형태를 사용함으로서 더 간단한 형태의 function을 만들 수 있음
function hiThere(x) {
return x*2;
}
----------------------------
(x) => {
return x*2;
}
-----------------------------
x => x*2
-----------------------------
function setUp() {
createCanvas(600,400);
background(0);
let button= createButton('press');
button.mousePressed(changeBackground);
function changeBackground () {
background(random(255));
}
function setUp() {
createCanvas(600,400);
background(0);
let button= createButton('press');
button.mousePressed(() => background(random(255)));
}
------------------------
2. Privacy :
- 변수가 선언된 곳의 바깥에서 불러올때 쓸 수없게 하는 것으로 할수 있다.
- _(underscore)를 변수 앞에 써서 설정할 수 있음
3. Getter :
- 객체의 프로퍼티를 가져오는 함수
let obj = {
get propName() {
},
let user = {
name: "John",
surname: "Smith",
get fullName() {
return `${this.name} ${this.surname}`;
}
};
alert(user.fullName);
4. Setter
- 객체의 프로퍼티를 쳇팅하는 함수, value로 프라퍼티 값을 할당할때 실행함
const robot = {
_model: '1E78V2',
_energyLevel: 100,
_numOfSensors: 15,
get numOfSensors(){
if(typeof this._numOfSensors === 'number'){
return this._numOfSensors;
} else {
return 'Sensors are currently down.'
}
},
set numOfSensors(num){
if(typeof num==='number'&& num>=0) {
this._numOfSensors = num;
} else {
console.log('Pass in a number that is greater than or equal to 0');
}
}
};
robot.numOfSensors = 100;
console.log(robot.numOfSensors);