객체 생성
일반적인 방법
var emptyObject = {};
console.log(typeof emptyObject); // object
var person = {
name: 'Lee',
gender: 'male',
sayHello: function () {
console.log('Hi! My name is ' + this.name);
}
};
console.log(typeof person); // object
console.log(person); // {name: "Lee", gender: "male", sayHello: ƒ}
person.sayHello(); // Hi! My name is Lee
Object 생성자 함수
// 빈 객체의 생성
var person = new Object();
// 프로퍼티 추가
person.name = 'Lee';
person.gender = 'male';
person.sayHello = function () {
console.log('Hi! My name is ' + this.name);
};
console.log(typeof person); // object
console.log(person); // {name: "Lee", gender: "male", sayHello: ƒ}
person.sayHello(); // Hi! My name is Lee
생성자 함수
위의 두 방식으로 객체를 생성하는 것은 프로퍼티 값만 다른 여러 개의 객체를 생성할 때 불편하다. 동일한 프로퍼티를 갖는 객체임에도 불구하고 매번 같은 프로퍼티를 기술 해야한다.
var person1 = {
name: 'Lee',
gender: 'male',
sayHello: function () {
console.log('Hi! My name is ' + this.name);
}
};
var person2 = {
name: 'Kim',
gender: 'female',
sayHello: function () {
console.log('Hi! My name is ' + this.name);
}
};
생성자 함수를 사용하면 객체를 생성하기 위함 템플릿처럼 사용하여 프로퍼티가 동일한 객체 여러개를 편하게 만들 수 있다.
// 생성자 함수
function Person(name, gender) {
this.name = name;
this.gender = gender;
this.sayHello = function(){
console.log('Hi! My name is ' + this.name);
};
}
// 인스턴스의 생성
var person1 = new Person('Lee', 'male');
var person2 = new Person('Kim', 'female');
console.log('person1: ', typeof person1);
console.log('person2: ', typeof person2);
console.log('person1: ', person1);
console.log('person2: ', person2);
person1.sayHello();
person2.sayHello();
생성자 함수는 암묵적인 약속으로 함수의 첫 글자를 대문자로 한다.
function Person(name, gender) {
var married = true; // private
this.name = name; // public
this.gender = gender; // public
this.sayHello = function(){ // public
console.log('Hi! My name is ' + this.name);
};
}
var person = new Person('Lee', 'male');
console.log(typeof person); // object
console.log(person); // Person { name: 'Lee', gender: 'male', sayHello: [Function] }
console.log(person.gender); // 'male'
console.log(person.married); // undefined
생성자 함수 this에 연결되어 있는 프로퍼이와 메소드는 외부에서 참조가 가능하다.
프로퍼티 또는 메소드명 앞에 기술한 this는 생성자 함수가 생성할 인스턴스(위 코드에서 person)을 가리킨다.
생성자 함수 내부의 일반변수는 외부에서 참조가 불가능하다.
프로퍼티 값 갱신
var person = {
'first-name': 'Cheolhun',
'last-name': 'Kim',
gender: 'male',
};
person['last-name'] = 'Bae';
console.log(person['last-name'] ); // 'Bae'
프로퍼티 동적 생성
var person = {
'first-name': 'Cheolhun',
'last-name': 'Bae',
gender: 'male',
};
person.age = 20;
console.log(person.age); // 20
프로퍼티 삭제
var person = {
'first-name': 'Cheolhun',
'last-name': 'Bae',
gender: 'male',
};
delete person.gender;
console.log(person.gender); // undefined
delete person;
console.log(person); // Object {first-name: 'Cheolhun', last-name: 'Bae'}
'Tech Interview > Javascript' 카테고리의 다른 글
#9. async & await (0) | 2020.02.13 |
---|---|
#8. Promise (0) | 2020.02.12 |
#7. 콜백 함수와 콜백함수를 이용한 비동기 처리 (0) | 2020.02.12 |
#6. Arrow Function (0) | 2020.02.01 |
#5. 함수 호출 방식에 의해 결정되는 this (0) | 2020.02.01 |
댓글