Javascript

자바스크립트 객체

M9M9 2020. 8. 21. 01:04

오늘은 객체에 대해 정리해보겠다.

 

 

자바스크립트는 일반 정적 언어들(c#, java, c++ 등)과 달리 class를 통해 객체를 생성하지 않아도 된다.

ES6부터 class 문법이 추가돼서 class를 통해 객체를 생성할 수 있지만, 자바스크립트는 기본적으로 프로토타입 기반이기 때문에 굳이 class를 사용하지 않아도 된다!

 

일단 객체를 생성해보겠다.

 

let car={
    gear:1,
    speed:150,
    name:'m9 car',
};

리터럴 표현으로 객체를 생성해보았다.

 

객체에 대해 설명하기 앞서 '리터럴'을 설명해보자면, 

 

-리터럴이란 소스 코드의 고정된 값을 대표하는 용어다.(위키백과)

- 즉, 변수, 상수, 객체 등에 저장되는 값들의 표현 방식이면서 이 코드에서는 car={...} 의 값들을 리터럴로 표현한 것이다.

- {} 사용해서 객체를 생성한 것을 객체 리터럴이라고 생각하면 쉽다.

 

속성(property)

먼저, 위의 코드는 car이라는 객체를 생성한 것이다. 

그리고 객체는 속성들의 집합으로 이루어져 있는데, 

이 코드에서의 속성은 gear:1 , speed:150 , name:'minkoo car'이다. 

속성은 ,(콤마)를 통해 구분 짓는다.

그래서 obj1의 객체는 3개의 속성을 가지고 있다.

 

 

키(key)와 값(value)

객체의 속성은 키와 값으로 이루어져 있다.

위의 코드에서 key는 gear, speed, name를 뜻하고

값은 1 , 150, 'm9 car' 을 뜻한다. 

 

 

 

객체 안의 함수(메소드)와 객체

객체는 정수와 문자열 속성 이외에도 함수와 객체도 속성으로 가질 수 있다.

let objFunctionObject={
    a1:3,
    func: ()=>{
        console.log('저는 메소드에요!');
    },
    innerObj:{
        inObj1:'나는',
        inObj2:'내부객체!',
    },
};

objFunctionObject.func();  //'저는 메소드에요!' 
console.log(objFunctionObject.innerObj.inObj1); //나는
console.log(objFunctionObject.innerObj.inObj2); // 내부객체!

참고로 함수가 객체 안에 속성 값으로 있으면 그 함수는 '메소드'라고 부른다.

그리고 출력하면 주석으로 표시한 결과 값들을 볼 수 있다.

 

 

객체 속성 동적으로 추가, 삭제

 

속성 추가

 

자바스크립트의 객체는 내용을 동적으로 추가, 삭제할 수 있다.

먼저, 위의 코드에서 동적으로 속성을 추가해보겠다.

 

let objFunctionObject={
    a1:3,
    func: ()=>{
        console.log('저는 메소드에요!');
    },
    innerObj:{
        inObj1:'나는',
        inObj2:'내부객체!',
    },
};

objFunctionObject.addProperty='addProperty';   //동적으로 객체 속성 추가

objFunctionObject.func();  //'저는 메소드에요!' 
console.log(objFunctionObject.innerObj.inObj1); //나는
console.log(objFunctionObject.innerObj.inObj2); // 내부객체!
console.log(objFunctionObject.addProperty); //addProperty

기존의 objFunctionObject 객체에 addPropery 속성을 추가하였고, 

속성을 console로 출력하니 잘 출력된 모습을 볼 수 있다.

 

 

빈 객체에서도 여러 개의 동적 속성을 추가할 수 있다.

let person={};     // let person=new Object(); 이 방식으로도 빈 객체를 생성할 수 있다.
person.age=10;
person.height=180;
person.sex='man';

console.log(person.age); //10
console.log(person.sex); //man
console.log(person.height); //height
console.log(person); // { age: 10, height: 180, sex: 'man' }

이런 식으로 빈 객체를 생성하고, 동적으로 속성을 추가할 수도 있다.

 

 

속성 삭제

 

속성 추가를 알아봤으니 속성 삭제도 알아보겠다. 

 

삭제는 간단하다. 

속성 앞에 delete 키워드만 붙이면 된다.

 

let person={};     // let person=new Object(); 이 방식으로도 빈 객체를 생성할 수 있다.
person.age=10;
person.height=180;
person.sex='man';

console.log(person.age); //10
console.log(person.sex); //man
console.log(person.height); //height
console.log(person); // { age: 10, height: 180, sex: 'man' }


delete person.age;
delete person.sex;
console.log(person); //{ height: 180 }

속성 추가 코드에서 delete person.age, delete person.sex 코드만 추가하였다. 

속성 앞에 delete 키워드를 붙인 모습을 볼 수 있고, 

객체를 출력하니 age와 sex에 해당하는 속성이 삭제됐다.

 

 

 

생성자 함수를 이용한 객체 생성

함수를 이용하여 객체를 생성할 수도 있는데, 이때는 객체를 생성할 때 사용하는 'new' 키워드를 사용해야 한다.

cf) new 키워드를 통해 생성자 함수들을 호출하여 객체를 만들 수 있다.(클래스의 생성자함수(constructor), 일반 함수)

만약 일반 함수를 new 키워드를 통해 생성하면, 함수에 대한 객체가 생성되고, 그 함수는 생성자 함수라고 칭한다.

 

 

function Student(grade,age){
    this.grade=grade;
    this.age=age;
    this.changeGrade= ()=>{   //함수 안에 함수가 포함될 수 있다.
        return grade-10;
    }
    
}

const StudentObj = new Student(90,18);
StudentObj.height=174; // height 속성 추가  
//함수를 통해 객체를 생성할 때도 속성을 동적으로 추가할 수 있다.

console.log(StudentObj); //Student { grade: 90, age: 18 }
console.log(StudentObj.age); //18
console.log(StudentObj.height); //174
console.log(StudentObj.changeGrade()); //80  

 

 

만약 new 키워드를 사용하지 않고 함수를 호출한다면?

function Student(grade,age){
    this.grade=grade;
    this.age=age;
}


const StudentObj2=Student(6,36);
console.log(StudentObj2); //undefined
console.log(StudentObj2.grade); // TypeError: Cannot read property 'grade' of undefined

제대로 작동하지 않는다. 

객체를 생성하기 위해 만든 생성자 함수를 new 키워드를 사용하지 않고 함수만 호출하게 되면 오류가 발생한다.

오류가 발생하는 이유는 일반 함수와 생성자 함수의 호출 시 this 바인딩 방식이 다르기 때문인데, 

this 관련은 다음에 따로 정리하겠다.

 

 

Class를 통한 객체 생성

 

마지막으로 class를 통해 객체를 생성할 수도 있다.

 

class Me{
    constructor(name,age,height){
        this.name=name;
        this.age=age;
        this.height=height;
        this.weight=60;
    }
};

const myObj=new Me('m9',27, 174);
console.log(myObj); //Me { name: 'm9', age: 27, height: 174, weight: 60 }
myObj.grade='A';
console.log(myObj); // Me { name: 'm9', age: 27, height: 174, weight: 60, grade: 'A' }

class도 동적으로 객체 속성을 추가할 수 있다.

 

 

마치며

확실히 정리하길 잘했다.

 

정리하며 delete 키워드와 객체 속성 삭제도 배우고,

생성자 함수를 활용하여 객체를 생성할 수도 있다는 것을 배웠다.