(1) 객체
- 키와 값을 가지는 프로퍼티(property)로 구성되어 있으며, 프로퍼티의 값이 함수일 경우, 이를 메소드라 한다.
- 프로퍼티를 열거할 때 순서를 보장하지 않는다.
- 프로퍼티를 중복 선언 할 수 없다.
- 프로퍼티 키는 문자열이나 symbol값이 지정되며 이외의 값은 암묵적으로 타입이 문자열로 변환된다.
- 객체의 생성 방법 (리터럴, Object(), 생성자 함수)
//-------리터럴-----
var a = {
name : "wangi",
age : 26
}
console.log(typeof(a), a); // object {name: "wangi", age: 26}
//-------Object()----
var b = new Object(); // Object 생성자 함수
b.name = "eddy"; // 프로퍼티 추가
b.gender = 'male';
console.log(typeof(b), b); // object {name: "eddy", gender: "male"}
//-------생성자 함수----
function information(name, age) { // 객체 생성자 함수 선언
this.name = name;
this.age = age;
};
var a = new information("wangi", 26); // 객체 생성
var b = new information("eddy", 25); // 객체 생성
console.log(typeof(a), a); // object information{name: "wangi", age: 26}
console.log(typeof(b), b); // object information{name: "eddy", age: 25}
(2) 객체의 접근
- value로 접근하는 방법은 마침표로 접근, 괄호로 접근 두가지가 있다.
var information = {
name: 'eddy',
age: 26,
hello: function(){
return '이름은 ${this.name}이고, 나이는 ${this.age}입니다.';
}
};
//----- 마침표로 접근----
console.log(information.name); // 'eddy'
console.log(information.age); // 26
console.log(information.hello()); // '이름은 eddy이고, 나이는 26입니다.'
//------ 괄호로 접근-----
console.log(information['name']); // 'eddy'
console.log(information['age']); // 26
console.log(information['hello']()); // '이름은 eddy이고, 나이는 26입니다.'
console.log(information['male']); // undefined 객체에 존재하지 않는 key경우에 undefined 반환
(3) 객체의 추가, 변경 및 삭제
- 객체에 존재하는 key에 새로운 값을 할당하면 값이 변경된다.
- 객체에 존재하지 않는 key에 새로운 값을 할당하면 값이 추가된다.
- delete를 사용하여 키를 삭제할 수 있다.
var information = {
name: 'eddy',
age: 26
};
information.age = 25; // 변경
console.log(information.age); // 25
information.gender = 'male'; // 추가
console.log(information.gender); // male
delete person.gender; // 삭제
console.log(information.gender); // undefined
(4) 객체 순회
- for-in문을 사용하여 객체의 키를 순회한다.
- for-in은 key 순회 목적이므로 배열에는 적합하지 않다.
- 순회 순서는 보장되지 않는다.
var information = {
name: 'eddy',
age: 26,
gender: 'male'
};
for (var key in information ) {
console.log(key + ': ' + information [key]);
}
var array = ['a', 'b'];
for (var index in array) {
console.log(index + ': ' + array[index]);
}
(5) Pass-by-reference, Pass-by-value
- Pass-by-reference : 객체 타입의 데이터에서 나옴, 객체는 참조 방식으로 전달하여 주소가 공유되는 것을 의미한다.(값이 복사되는 것이 아니다.)
- Pass-by-value : 원시 타입의 데이터에서 나옴, 원시 타입은 값이 복사 되어 전달한다.
var a = [1,2,3]
var b = a
a[0] = 10000
console.log(b) // [10000, 2, 3] a의 주소를 참조하고 있기 때문
var a = 10
var b = a
a = 1
console.log(a, b); // 1, 10 값이 그대로 복사 되어 전달 되기 때문
'JavaScript' 카테고리의 다른 글
[JavaScript] 함수 (1) | 2023.10.12 |
---|---|
[JavaScript] 객체 변경 불가성 (1) | 2023.10.11 |
[JavaScript] 타입변환과 단축평가 (0) | 2023.09.27 |
[JavaScript] 제어문 (0) | 2023.09.27 |
[JavaScript]연산자 (0) | 2023.09.26 |