[javascript] 객체 프로퍼티(속성) 메소드 삭제 / 나열 / 추가
by mini_min[javascript] 객체 프로퍼티(속성) 메소드 삭제 / 나열 / 추가
✔️ 객체 프로퍼티 지우기
: delete + 객체. 프로퍼티명
var obj = {
name: '이이이',
age:20
};
console.log(obj.name);
console.log(obj.age);
//프로퍼티 제거
delete obj.age;
console.log(obj.age); //undefined
💡 결과는 undefined 로 나온다.
✔️ 객체 프로퍼티 접근 및 나열
var obj = {
name:'고고고',
age:20,
result:function(){
return this.age >= 19? '성인':'초딩';
}
};
//객체의 프로퍼티 접근
console.log(obj.name); //도트 표기법
console.log(obj['name']); //대괄호 표기법으로 접근
// 메소드 접근
console.log(obj.result());
//객체의 프로퍼티 나열
for(let ob in obj){
//ob : 속성명
console.log(ob, obj[ob]);
}
✔️ 객체 프로퍼티 및 메소드 추가
function User(name, age){ //생성자함수. 필드를 가질 수 있다.
this.name = name; //필드.
this.age = age;
}
var obj = new User('자바',20); //obj
obj.score = 80; // obj <- score property add!
obj.state = function(){
return this.age>=19? 'adult':'child';
}; //obj <- method add!
💡 메소드명에 값까지 간단하게 추가가능하고,
아래처럼 메소드도 추가 가능하다. (새로운 메소드 이름은 state 가 된다.)
없는 프로퍼티와 메소드는 console.log(obj2.score); // undefined!! console.log(obj2.state); // error!
'JavaScript' 카테고리의 다른 글
[javascript] 클래스(class) 선언 / 상속 / 프라이빗 (2) | 2022.09.25 |
---|---|
[javascript] 객체 프로토타입에 프로퍼티, 메소드 추가 / 정적메소드 (0) | 2022.09.22 |
[javascript] 객체 - this / 호출 방법에 따른 this / form 요소에서 this (0) | 2022.09.22 |
[javascript] 객체 정의 / 프로토타입 기반 언어 / 객체 만들기 (생성) (0) | 2022.09.22 |
[javascript] 브라우저 객체 모델 / window 객체 / document 객체 (0) | 2022.09.21 |
블로그의 정보
개발자 미니민의 개발로그
mini_min