객체
자바스크립트의 기본타입은 객체이다.
객체는 이름과 값으로 구성된 프로퍼티의 정렬되지 않은 집합이라고 할 수 있다.
프로퍼티의 값으로는 함수가 올 수 있는데, 함수값이 들어 있는 프로퍼티를 메소드(method)라고 한다.
객체는 { }를 이용해 만들 수 있고 '키:값' 쌍으로 구성된 프로퍼티를 여러개 넣을 수 있다.
서랍장 안 파일은 프로퍼티, 파일 각각에 붙어 있는 이름표는 객체라고 생각하면 쉽다
생성
기본적으로 쓰이는 방법은 밑에와 같다
var 객체이름 = {
프로퍼티1이름 : 프로퍼티1의값,
프로퍼티2이름 : 프로퍼티2의값,
...
};
예제
var car = { //객체 선언
type:"Fiat", // 키:값
model:"500",
color:"white"
};
생성 방법 1,2,3
//1
var grades = {'cemy': 10, 'stormy':6, 'windy':80};
//2
var grades = {};
grades['cemy']=10; //grades.cemy=10
grades['stotmy'] = 6; //grades.stromy=6
grades['windy'] = 80; //grades.windy=80
//3
var grades = new Obkect();
grades.cemy=10
grades.stromy=6
grades.windy=80
자바스크립트 객체에 메소드와 속성 사용
1) 객체.메서드() - 객체의 메서드를 실행
2) 객체.키; - 객체의 속성값을 가져옴
3) 객체.키=값; - 객체의 속성값을 변환
객체의 프로퍼티 참조
객체이름.프로퍼티이름
또는
객체이름["프로퍼티이름"]
예제
var person = {
name: "홍길동", // 이름 프로퍼티를 정의함.
birthday: "030219", // 생년월일 프로퍼티를 정의함.
pId: "1234567", // 개인 id 프로퍼티를 정의함.
fullId: function() { // 생년월일과 개인 id를 합쳐서 주민등록번호를 반환함.
return this.birthday + this.pId;
}
};
person.name // 홍길동
person["name"] // 홍길동
new 연산자를 사용하여 객체 생성 (생성자를 이용한)
var day = new Date(); // new 연산자를 사용하여 Date 타입의 객체를 생성함.
document.write("올해는 " + day.getFullYear() + "년입니다.");
객체의 메소드 참조
객체이름.메소드이름()
예제
var person = {
name: "홍길동",
birthday: "030219",
pId: "1234567",
fullId: function() {
return this.birthday + this.pId;
}
};
person.fullId() // 0302191234567
person.fullId; // function () { return this.birthday + this.pId; }
참조
방법 1, 2
//1
var grades = {'cemy':10, 'stormy':6, 'windy':80};
alert(grades['windy']);
alert(grades.windy);
//2
var grades = {'cemy':10, 'stormy':6, 'windy':80};
for(key in grades){
document.write("key: "+key+", value: "+grades[key]+"<br>");
}
this 키워드
자바스크릡트에서 this는 해당 키워드가 사용된 자바스크립트 코드 영역을 포함하고 있는 객체를 뜻함
메소드 내부에서 사용된 this는 해당 메소드를 포함하는 객체를 뜻하고
객체 내부에서 사용된 this는 객체 자신을 가리킨다
this는 변수가 아닌 키워드이기에 사용자가 임의로 가리키는 값을 바꿀수 없다
function Dog(color, name, age) {
this.color = color;
this.name = name;
this.age = age;
}
var myDog = new Dog("흰색", "마루", 1);
delete myDog.age; // age 프로퍼티를 삭제함.
// age 프로퍼티가 삭제되었기 때문에 undefined를 출력함.
document.write("우리집 강아지의 나이는 " + myDog.age + "입니다.");
다가서는 OOP(Obkect-Oriented Programmin: 객체지향 프로그래밍)
var grades = {
list:{'cemy': 10, 'stormy':6, 'windy':80},
show:function(){
for(var name in this.list){
document.write(name+':'+this.list[name]+"<br>");
}
}
};
grades.list.windy();
grades.show();
참고
https://webclub.tistory.com/390
https://jusungpark.tistory.com/33
https://ko.javascript.info/object
https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Basics
'JavaScript > 기본' 카테고리의 다른 글
객체 (최소, 최대 평균) (0) | 2022.06.29 |
---|---|
객체 (생성자) (0) | 2022.06.24 |
자바스크립트 참고 사이트 (0) | 2022.06.23 |
이벤트 (0) | 2022.06.23 |
this - jQuery/ javascript 차이 (0) | 2022.06.23 |
댓글