Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 동적계획법
- Redis
- 분할정복
- 스프링부트
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- Spring Boot
- 영속성 컨텍스트
- 자바의 정석
- VMware
- 스프링 시큐리티
- spring security
- 캐시
- 호이스팅
- MongoDB
- sqld
- 다이나믹프로그래밍
- 정보처리기사
- 이벤트루프
- JPA
- 게시판
- 깃허브
- 실행 컨텍스트
- 스프링 부트
- document database
- NoSQL
- 정처기
- 레디스
- SQL
- github
- in-memory
Archives
- Today
- Total
FreeHand
객체 본문
객체 생성
1. 객체 리터럴
let person1 = {
name: 'Jin',
age: 25,
toString: function() {
return '{name: ' + this.name + ', age: ' + this.age + '}';
}
};
console.log(`name: ${person1.name}`); // name: Jin
console.log(`age: ${person1.age}`); // age: 25
console.log(person1.toString()); // {name: Jin, age: 25}
2. Object() 생성자
let person2 = new Object(); // let person2 = {};
person2.name = 'Lee';
person2.age = 23;
person2.toString = function() {
return '{name: ' + this.name + ', age: ' + this.age + '}';
}
console.log(`name: ${person2.name}`); // name: Lee
console.log(`age: ${person2.age}`); // age: 23
console.log(person2.toString()); // {name: Lee, age: 23}
3. 사용자 정의 생성자
function Person(name, age) {
this.name = name;
this.age = age;
this.toString = function() {
return '{name: ' + this.name + ', age: ' + this.age + '}';
}
}
let person3 = new Person('Kim', 20);
console.log(`name: ${person3.name}`); // name: Kim
console.log(`age: ${person3.age}`); // age: 20
console.log(person3.toString()); // {name: Kim, age: 20}
prototype
모든 객체는 prototype 객체를 참조함.
객체는 prototype 객체의 프로퍼티를 상속받음.
let person = new Person('Jin', 25);
Person.prototype.hobby = 'walk';
Person.prototype.getHobby = function() {
return this.name + "의 취미는 " + this.hobby + "입니다.";
};
console.log(person.getHobby()); // Jin의 취미는 walk입니다.
constructor
모든 객체는 constructor 프로퍼티를 갖는다. 생성자를 참조함.
객체의 타입을 알 수 있고 객체 생성도 가능함
let person = new Person('Jin', 25);
// constructor는 생성자를 참조함
if(person.constructor === Person) {
console.log("person.constructor === Person"); // person.constructor === Person
}
// constructor를 사용한 객체 생성
let person2 = new person.constructor('Kim', 20); // new Person('Kim', 20);
console.log(person2.toString()); // {name: Kim, age: 20}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
print() {
console.log(`이름: ${this.name}, 나이: ${this.age}`);
}
}
let people = [
new Person('Jin', 25),
new Person('Lee', 25),
new Person('Kim', 20)
];
for(let person of people) {
person.print();
}
// 이름: Jin, 나이: 25
// 이름: Lee, 나이: 25
// 이름: Kim, 나이: 20
'Language > Javascript' 카테고리의 다른 글
[Javascript] 이벤트 루프와 비동기 처리 (0) | 2024.09.27 |
---|---|
[Javascript] 실행 컨텍스트 (2) | 2024.09.25 |
Event (0) | 2023.10.26 |
Javascript DOM (0) | 2023.10.26 |