#TIL (May 6th, 스물한번째 이야기)

Jung Hyun Kim·2020년 5월 6일
0

Javascript (advanced object)

Advanced Object


1. Arrow Function :

  • Arrow function 형태를 사용함으로서 더 간단한 형태의 function을 만들 수 있음

function hiThere(x) {
  return x*2;
} //여기서 
----------------------------
(x) => {

return x*2;
}  // 이렇게 변경 된 것을 arrow function 이라고 함 심지어 여기서 
-----------------------------

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() {
 // getter, obj.propName을 실행할 때 실행되는 코드
},

let user = {
name: "John",
surname: "Smith",

get fullName() {
  return `${this.name} ${this.surname}`;
}
};

alert(user.fullName); // John Smith

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){ //setter는 항상 argus있어야함
           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);
profile
코린이 프론트엔드 개발자💻💛🤙🏼

0개의 댓글