객체 안의 함수

화살표함수에서는 this를 읽을 수 없음(? 더 알아보기) function 함수에서 this는 자기가 속해있는 곳으로 연결

// 예시1
const dody = {
    name: 'dody', 
    age: 30, 
    say: function saying(){
    	console.log(this.name);
    }
}

// 예시2
const dody = {
    name: 'dody', 
    age: 30, 
    say: function(){
    	console.log(this.name);
    }
}

// 예시3
const dody = {
    name: 'dody', 
    age: 30, 
    say(){
    	console.log(this.name);
    }
}

dody.say(); // dody 출력

getter, setter

getter: 값을 조회할 때 생성하는, 

setter: _name으로 이름을 짓는건, setter함수와 겹치지 않기 위해, param를 무조건 받아와야 함.

둘다 ()로 호출하지 않는다. get, set 둘 함수명이 같아도 된다. 배운 예시의 모든것은 아래와 같다. 

const number = {
    _a: 1, 
    -b: 2, 
    sum: 3, 
    calculate(){
    	this.sum = this._a + this._b
    },
    get a(){
    	return this._a;
    }
    get b(){
    	return this._b;
    }
    set a(value){
    	this._a = value; 
        this.sum = value + this._b
    }
    set b(value){
    	this._b = value; 
        this.sum = value + this._a
    }
}

// ex
number.a = 10
number.b = 8

 

+ Recent posts