1. 객체(Object)
하나의 주제를 가지고 관련있는 프로퍼티(property)를 가지고 있는 집합
- 프로퍼티(property)
- 이름과 값으로 구성된 정렬되지 않은 집합
- 프로프티는 함수도 저장할 수 있음 -> 프로퍼티 메서드
2. 객체 생성하는 방법
- 리터럴 표기법
const 객체명 = {
프로퍼티명1: 값1,
프로퍼티명2: 값2,
.... ,
프로퍼티명n: function(){
}
}
|
<body>
<h2> 리터럴 표기법 </h2> <script>
const Rucy={
name:'루시',
age:14,
color:'white',
birthday:'20091210',
getBirthday:function(){ //메소드 프로퍼디 (익명함수 생성)
return this.birthday; //birthday 리턴
}
}
//객체를 호출1 // Rucy 객체의 name 속성에 직접적으로 접근
console.log(Rucy.name);
console.log(Rucy.age);
console.log(Rucy.color);
console.log(Rucy.birthday);
console.log(Rucy.getBirthday);// 함수 자체를 출력
console.log(Rucy.getBirthday());
// 함수를 실행(birthday) //20091210 console.log( '==============' );
//객체를 호출2 //Rucy 객체의 name 속성에 접근하고 있지만, 속성 이름을 따옴표로 묶은 문자열로 지정 console.log( Rucy['name'] );
console.log( Rucy['age'] );
console.log( Rucy['color'] );
console.log( Rucy['birthday'] );
console.log( Rucy['getBirthday'] );
console.log( Rucy['getBirthday']() );
console.log( '==============' );
for(let i in Rucy){
console.log(`i:${i}, Rucy[${i}:${Rucy[i]}]`)
}
// ${i} -> name, age, color, birthday, getBirday // ${Rucy[i]} -> 루시, 14, white, 20091210,주소값
</script>
</body>
|
----------------------------------------------------------------------------- ----------------------------------------------------------------------------- |
- 생성자를 이용
- 객체를 만드는 함수
- 사용하는 이유
- new 연산자를 이용하여 객체를 생성하고 초기화할 수 있음
- 객체를 생성할 때 사용하는 함수를 생성자라고 함
- 새롭게 생성되는 객체를 초기화하는 역할
- 같은 형태의 객체를 여러개 생성할 때 유리
function 생성자(매개변수, 매배변수2, ...){
this.프로퍼티명1 = 값1
this.프로퍼티명2 = 값2
...
this.프로퍼티명n = function(){
프로퍼티가 호출되면 실행할 문장
}
}
const 객체명1 = new 생성자명(값1, 값2, ...)
const 객체명2 = new 생성자명(값1, 값2, ...)
|
<body>
<h2> 생성자를 이용한 객체 </h2> <script>
function Dog(name,color){
this.name=name;
this.color=color;
this.eat=function(){
return `${this.name}이/가 냠냠이를 먹습니다.`;
}
}
const PPomi = new Dog('뽀미','흰색');
console.log( PPomi.name );
console.log( PPomi.color );
console.log( PPomi.eat );
console.log( PPomi.eat() );
</script>
</body>
|
- 클래스를 이용
- ECMA Script6에 추가된 객체 생성 방법
- 내부적으로 생성자를 이용한 객체 생성 방법과 동일하게 작동
const 클래스명 = class {
constructor(매개변수1, 매개변수2, ...)
this.프로퍼티명1 = 값1,
this.프로퍼티명2 = 값,
}
메소드명(매개변수1, 매개변수2, ...) {
메소드가 호출되면 실행할 문장
}
}
const 객체명1 = new 클래스명(값1, 값2, ...)
const 객체명2 = new 클래스명(값1, 값2, ...)
|
<body>
<h2> 클래스를 이용한 객체 </h2> <script>
const Student = class{
constructor(name,hp,age){
this.name=name;
this.hp=hp;
this.age=age;
}
getName() {
return `이름은 ${this.name}입니다.`;
}
}
const apple =new Student('김사과','01000001111',20);
console.log(apple.name);
console.log(apple.hp);
console.log(apple.age);
console.log(apple.getName);
console.log(apple.getName());
</script>
</body>
|
3. 상속
클래스 기반의 객체지향 언어와 다름
자바스크립트는 프로토타입 기반의 객체지향언어
- 프로토타입(prototype)
- 모든 객체는 프로토타입아리는 객체를 가지고 있음
- 모든 객체는 프로토타입으로부터 프로퍼티와 프로퍼티 메서드를 상속받음
- 모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받으며 상속되는 정보를 제공하는 객체를 프로토타입이라고 함
const dog = new dog() // Dog.prototype, Object.prototype // 루시객체 생성자, 함수 추가 Rucy.family='포메라니안';
Rucy.getFamily=function(){
return this.family;
}
// 프로토타입 생성자, 함수 추가 Dog.prototype.owner = '김사과';
Dog.prototype.run=function(){
return this.name+'이/가 달립니다!';
}
|
기본 메서드나 기본 함수를 제공하는 표준 함수 스페셜메소드를 제공하는 오브젝트 |
<body>
<h2> prototype </h2> <script>
<h2>prototype</h2>
<script>
function Dog(color,name,age){
this.color=color;
this.name=name;
this.age=age;
}
const Rucy=new Dog('white','루시',14);
console.log(Rucy); //Dog 객체 생성
console.log( '==============' );
console.log(`이름:${Rucy.name}`); // 루시
console.log(`색상:${Rucy.color}`); // white
console.log(`나이:${Rucy.age}`); // 14
console.log( '==============' );
Rucy.family='포메라니안';
Rucy.getFamily=function(){
return this.family;
}
console.log(`종:${Rucy.family}`); // 종: 포메라니안
console.log(`getFamily:${Rucy.getFamily()}`);
// getFamily: 포메라니안 // 새로운 프로퍼티 생성, 루시객체에서 만들어짐
// 객체에만 만들어짐, Dog는 영향을 주지 않음
console.log('====================')
const PPomi=new Dog('white','뽀미',16);
console.log(`이름:${PPomi.name}`); // 뽀미
console.log(`색상:${PPomi.color}`); // white
console.log(`나이:${PPomi.age}`); // 16
console.log('====================') // console.log(`종:${PPomi.family}`);
// console.log(`getFamily:${PPomi.getFamily()}`);
// 프로토타입(Dog)에 객체가 없기 때문에 에러!
console.log('====================')
Dog.prototype.owner = '김사과';
Dog.prototype.run=function(){
return this.name+'이/가 달립니다!';
}
console.log(`소유자: ${Rucy.owner}`); // 소유자: 김사과
console.log(`run: ${Rucy.run()}`); // run:루시이/가 달립니다!
console.log(`소유자: ${PPomi.owner}`); // 소유자: 김사과
console.log(`run: ${PPomi.run()}`); // run:뽀미이/가 달립니다!
</script>
</body>
|
무조건 상속되는 객체_Prototype : Object ------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- 에러 -------------------------------------------------------------------------------------------------- |
'Web > JavaScript' 카테고리의 다른 글
09. 문서객체모델, 노드(Node) (0) | 2024.04.16 |
---|---|
08. 내장객체 (0) | 2024.04.16 |
06. 함수(Function) (0) | 2024.04.16 |
05. 배열(Array) (0) | 2024.04.16 |
04. 연산자, 제어문, 반복문 (0) | 2024.04.16 |