반응형
객체의 속성 추가와 제거
처음 객체를 생성하는 시점 이후에 속성을 추가하거나 제거하는 것을 '동적으로 속성을 추가한다'또는 '동적으로 속성을 제거한다'고 표현합니다.
속성 추가
빈 객체 생성하기 예
var student = {};
동적으로 속성 추가하기 예
var student = {};
// 객체에 속성 추가하기
student.name = 'shiro';
student.hobby = '컴퓨터';
student.ability = '컴퓨터';
동적으로 메서드 추가하기 예
var student = {};
student.name = 'shiro';
student.hobby = '컴퓨터';
student.ability = '컴퓨터';
student.toString = function() {
var output = '';
for(var key in this) {
if(key != 'toString') {
output += key + '\t' + this[key] + '\n';
}
}
return output;
}
console.log(student.toString());
/*
name shiro
hobby 컴퓨터
ability 컴퓨터
*/
메서드도 속성이므로 같은 방법으로 추가할 수 있습니다.
:: toString() 메서드 = 객체에 있는 속성을 출력하는 메서드
속성 제거
동적으로 객체의 속성을 제거할 때는 delete키워드를 사용합니다. delete키워드 뒤에 삭제하고자 하는 객체의 속성을 입력합니다.
:: 객체의 속성을 입력할 때는 typeof키워드처럼 괄호를 입력해도 되고 입력하지 않아도 됩니다.
객체의 속성 제거하기 예
var student = {};
student.name = 'shiro';
student.hobby = '컴퓨터';
student.ability = '컴퓨터';
student.toString = function() {
var output = '';
console.log(this);
for(var key in this) {
if(key != 'toString') {
output += key + '\t' + this[key] + '\n';
}
}
return output;
}
console.log(student.toString());
/*
name shiro
hobby 컴퓨터
ability 컴퓨터
*/
delete(student.hobby);
console.log(student.toString());
/*
name shiro
ability 컴퓨터
*/
delete student.ability;
console.log(student.toString());
/*
name shiro
*/
위 코드처럼 속성을 제거할 수 있습니다.
반응형
'JavaScript | TypeScript > Javascript 시작하기' 카테고리의 다른 글
[ Javascript ] 참조 복사와 값 복사 (0) | 2022.06.10 |
---|---|
[ Javascript ] 함수를 사용한 객체 생성 (0) | 2022.06.10 |
[ Javascript ] 객체 ( Object ) (0) | 2022.06.09 |
[ Javascript ] ECMAScript 6 (0) | 2022.06.08 |
[ Javascript ] 기본 매개변수 (0) | 2022.06.08 |