Front-End

vsoghlv@naver.com

자바스크립트 객체

자바 스크립트 객체 object 는 함수 혹은 클래스로 틀을 만들고 그 틀로 만들어낸다.(인스턴스) 여러 강의에서 붕어빵틀-Class, Function 과 붕어빵 -instance 으로 설명하는 경우가 많았다.

먼저 생성자 함수를 통한 객체 생성법을 보자.

//생성자 함수
function A(){};

const a = new A();
console.log(a, typeof a);//A {} 'obeject'
console.log(A());//undefined

//생성시 데이터 삽입
function B(name, age) {
    console.log(name, age);
}

const b = new B();//undefined
const c = new B('Sun', 28); //"Sun" 28 
console.log(B()); //undefined undefined undefined

객체에 속성-property 를 넣을 수 있는데 프로퍼티에는 값, 함수 등 여러 인자가 들어갈 수 있다.

//값을 속성으로 넣기
function A() {
    this.name = 'Sun';
}
const a = new A();
console.log(a); //A {name:Sun}

//함수를 속성으로 넣기
function B() {
    this.hello = function() {
        console.log('hello');
    }
}

new B().hello(); // 'hello'

이외에도 new Objcet()를 이용해서 객체를 만들수 있는데 이 방법은 그리 권장되지 않는다.

const a = new Object();
console.log(a, typeof a);// {} 'object

const b = new Object(true);
console.log(b, typeof b);// [Boolean : true] 'object'

const c = new Object({name : 'Sun'});
console.log(c, typeof c);//{name : 'Sun'} 'object'

혹은 객체리터럴 방식을 통해 변수에 바로 객체를 할당하는 방식으로도 사용가능하다.

const a = {};
console.log(a, typeof a);// {} 'object'

const c = {
    name: 'Sun',
    hello1() {
        console.log('hello1', this.name);
    }
    hello2 : function(){
        console.log('hello2', this.name);
    }
    hello3 = () => {
        console.log('hello3', this.name);
    }
}

c.hello1();//'hello1' Sun
c.hello2();//'hello2' Sun
c.hello3();//undefined

위의 예제에서 알 수 있듯이 화살표함수를 사용하는 경우 this가 가리키는 객체가 달라진다.

MDN 문서를 살펴보면 “ 화살표 함수는 자신의 this가 없습니다. 대신 화살표 함수를 둘러싸는 렉시컬 범위(lexical scope)의 this가 사용됩니다; 화살표 함수는 일반 변수 조회 규칙(normal variable lookup rules)을 따릅니다. 때문에 현재 범위에서 존재하지 않는 this를 찾을 때, 화살표 함수는 바로 바깥 범위에서 this를 찾는것으로 검색을 끝내게 됩니다. “ 라고 한다.

즉, 위의 화살표함수로 작성한 hello3의 this는 호출한 c가 아닌 c의 상위 컨택스트에서 this를 검색하기 때문에 undefinde라는 결과가 나오게 되는 것이다.