모던 자바스크립트 Deep Dive를 참고하여 학습,작성하였습니다.
1.객체(Object)
자바스크립트에서 객체는 키(key)과 값(value)으로 구성된 프로퍼티(Property)들의 집합이다.
프로퍼티값이 함수일때는 메소드라고 부른다.
1-1.프로퍼티(Property)
프로퍼티(Property)는 속성이라는 의미로 "key(키)" : "value(값)" 형태로 객체에 구분,할당된다.
프로퍼티는 프로퍼티키로 유일하게 식별가능하다.
2.객체 생성
2-1.객체 리터럴
{}를 통해 객체를 생성한다.
{}내부에 아무것도 기술하지않으면 빈 객체가 생성된다.
var human={
name:'KIM',
gender:'male',
walk:function(leng){
document.write(leng+"만큼걸었다.")
}
}
human.walk(10);
2-2.생성자 함수
생성자 함수를 사용하면 다른 언어에서 클래스를 사용하는것처럼 동일한 객체 여러개를 간편하게 생성할수있다.
new 키워드와 함께 생성자 함수를 통해 생성된 객체를 인스턴스라고 한다.
프로퍼티,메소드명앞의 this 키워드는 인스턴스를 가르킨다.
this 가 붙어있는 프로퍼티와 메소드는 public 을 가진다.
생성자 함수 내부에 선언된 일반 변수는 private다.
function Organism(name,life){
this.name=name;
this.life=life;
this.sayname=function(){
document.write(name+"<br>")
}
}
var cat= new Organism('cat',10);
var dog= new Organism('dog',30);
cat.sayname();
dog.sayname();
3.객체 프로퍼티 접근
3-1.프로퍼티 키(Key)
키값은 기본적으로 문자열값이다. 그러므로 문자열이 아닌값은 암묵적으로 문자열로 타입변환이 된다.
때문에 대부분의 경우에는 '' 를 생략가능하지만 유효한 이름이 아닌경우 따음표를 사용해야한다.
3-2.계산된 프로퍼티(computed property)
대괄호 []로 둘러쌓인 프로퍼티 키이다. 객체변수명에 미리 계산된 변수를 넣는다.
var name="first_name"
var test1={
'hi-hello':"sds",
//hi-hello:"sds", '-'연산자 때문에 안됨
[name]:"Kim",
}
document.write(test1.first_name)
3-3.프로퍼티 값
마침표(.) 표기법과 대괄호([]) 표기법이 있다.
키가 유효한 이름이 아닌경우 대괄호 표기법으로 읽어야한다.
var name="first_name"
var test1={
'hi-hello':"sds",
[name]:"Kim",
1: 10,
}
//document.write(test1.hi-hello)
//document.write(test1[hi-hello]);
document.write(test1['hi-hello']+"<br>")
document.write(test1.first_name)
//document.write(test1[first_name])
document.write(test1['first_name']+"<br>")
//document.write(test1.1+"<br>")
document.write(test1[1]+"<br>")
document.write(test1['1']+"<br>")
3-4.프로퍼티 값 갱신
var test1={
first_name:"Kim",
}
test1.first_name="PARK"
document.write(test1.first_name+"<br>")
test1['first_name']="JOE"
document.write(test1.first_name+"<br>")
3-5.프로퍼티 동적 생성
var test1={
first_name:"Kim",
}
test1.age= 20;
document.write(test1.age+"<br>")
4.for 문
4-1.for in
객체의 모든 프로퍼티에 대해 루프를 수행
var test3=['Kim','Park','JOE']
test3.age=20;
for(var index in test3){
document.write(test3[index]+"<br>")
}
4-2.for of
객체의 배열요소만을 순회
var test3=['Kim','Park','JOE']
test3.age=20;
for(var value of test3){
document.write(value+"<br>")
}
반응형
'FrontEnd > JavaScript' 카테고리의 다른 글
[JavaScript] 참조타입,원시타입 (0) | 2024.06.03 |
---|---|
[JavaScript] 배열 메소드 (0) | 2024.06.01 |
[JavaScript] 배열 (0) | 2024.06.01 |