본문 바로가기
JavaScript

JavaScript기초(22)_객체(2)

by DeBanker.K 2021. 10. 16.

1. new Object()

우선 빈 객체를 만들어 그 결과 값과 타입을 출력하면 아래와 같이 나온다.

const a = new Object();
console.log(a, typeof a);
[Running]
{} object

 

Object에 true를 넣고 똑같이 출력해보자.

const a = new Object(true);
console.log(a, typeof a);
[Running] 
[Boolean: true] object

a는 불리언 true라는 결과 값과 타입은 객체라고 나온다.

 

Object에 직접 리터럴 형태의 객체 값을 아래와 같이 넣으면 어떻게 될까?

const a = new Object({name : 'Kim'});
console.log(a, typeof a);
[Running] 
{ name: 'Kim' } object

우리가 흔히 아는 객체 형태 그대로 출력된다. 

 

 

2. 프로토타입 체인(.prototype)

아래의 예시를 잘 살펴보자.

function Person(name, age){
    this.name = name;
    this.age = age;
    this.hello = function(){
        console.log('hello', this.name, this.age);
    };
} 
/* name과 age라는 인자를 가지며 
   그속에는 hello, name, age를 출력하는 함수 hello 속성이 있는 함수 Person을 생섬. */

const p = new Person('Kim', 31); 
// 'Kim'과 31이라는 인자를 가지는 생성자함수로 객체 p 생성

p.hello();
console.log(p.toString());
console.log(Person.prototype);
console.log(Person.prototype.toString);
console.log(Person.prototype.constructor);
console.log(Person.hello);
console.log(Person.prototype.hello);
[Running] 
hello Kim 31          // p.hello();의 결과 값
[object Object]       // console.log(p.toString());의 결과 값
{}                    // console.log(Person.prototype);의 결과 값
[Function: toString]  // console.log(Person.prototype.toString);의 결과 값
[Function: Person]    // console.log(Person.prototype.constructor);의 결과 값
undefined             // console.log(Person.hello);의 결과 값
undefined             // console.log(Person.prototype.hello);의 결과 값

첫 줄 p.hello(); 는 정상적인 결과 값이 출력되었다.

두번 째 console.log(p.toString()); 에서 함수 Person에 toString이라는 속성이 없음에도 불구하고 결과 값이 출력되었다.

나머지 .prototype / .prototype.toString / .prototype.constructor 모두 함수 Person에 없는 것들이지만 정상 출력된다.

그러나 Person.hello / Person.prototype.hello 는 undefined로 인식한다. 이는 hello 가 객체로 생성되지 않았기 때문이다. 

 

hello는 Person 함수의 객체가 만들어지고 바로 그것의 프로퍼티(속성)으로 존재하는 것인데,

이를 통해서 'prototype'이라는 것은 hello 보다 더 안쪽에 존재하는 속성임을 알 수 있다. 

 

 

그래서 아래와 같이 'prototype'안에서 hello를 정의해보자.

function Person(name, age){
    this.name = name;
    this.age = age;
	//    this.hello = function(){
	//        console.log('hello', this.name, this.age);
	//    };
} 
/* name과 age라는 인자를 가지며 
   그속에는 hello, name, age를 출력하는 함수 hello 속성이 있는 함수 Person을 생섬. */
   
   Person.prototype.hello = function(){
    console.log('hello', this.name, this.age);
};
[Running] 
[Function (anonymous)]

출력 값 익명함수(anonymous function) 값으로 정상 출력된다.

hello에 따로 함수 명을 설정해주지 않았기 때무에 익명함수로 출력되는 것이다.

 

*일단 현재까지 봤을 때, 함수가 생성됨과 동시에 'prototype'이라는 것이 기본적으로 같이 생김을 알 수 있다.

'prototype'을 통해서 생성자 함수를 통해 만들어진 객체에 영향을 줄 수도 있는데, 더 나아가기전에 

다음 게시물에서 'Object', 'prototype'에 대한 개념을 좀 더 명확히하고 이후 내용을 전개하도록 하겠다.

 

 

'JavaScript' 카테고리의 다른 글

JavaScript 기초(24)_객체(4)  (0) 2021.10.21
JavaScript 기초(23)_객체(3)  (0) 2021.10.20
JavaScript기초(21)_객체(1)  (0) 2021.10.15
JavaScript기초(20)_함수(6)  (0) 2021.10.14
JavaScript기초(19)_함수(5)  (0) 2021.10.13

댓글