본문 바로가기
JavaScript

JavaScript기초(21)_객체(1)

by DeBanker.K 2021. 10. 15.

함수, 클래스 (틀) => 객체, 개체, object 

: 함수, 클래스 등의 틀을 이용해서 여러 객체(object)를 찍어내는 개념이다.

 

1. function 틀() {} => new 틀 ()

비어있는 생성자 함수를 만들어보자.

function A(){}
// 텅빈 함수 A 생성함.
const a = new A();
// 변수 a에 생성자함수 A를 선언함. = 객체 생성
console.log(a, typeof a);
// 생성된 객체 a 와 a의 타입을 출력함.
console.log(A());
// 함수 A() 자체를 출력함.
[Running] 
A {} object
undefined

객체 a를 출력하니 텅 빈 함수 'A {}'가 출력되었고, 'new A()'(생성자 함수)로 선언한 a의 타입은 'object'로 출력되었다.

함수 A() 가 텅 비어있기 때문에 마지막에 'undefined'로 출력되었다.

 

 

name과 age라는 매개변수를 2개 가지고 있는 함수를 만들어보자.

function A(name, age){
    console.log(name, age);
}
// name, age라는 인자(매개변수)를 가지면서 출력하는 함수 B 선언하였음.
const a = new A();
// 변수 b에 인자를 가지고 있지않은(매개변수가 없는) 생성자함수 B를 선언함. = 객체 생성
const b = new A('Kim', 31);
// 변수 c에 인자 kim, 31를 가진 (매개변수가 있는) 생성자함수 B를 선언함. = 객체 생성
console.log(A());
// 함수 A()) 자체를 출력함.
[Running] 
undefined undefined
Kim 31
undefined undefined
undefined

처음 객체 a를 출력할 때는 인자를 넣어주지 않았으므로 name, age 모두 'undefined'로 출력된다.

객체 b는 'Kim', '31'이라는 name, age 모두 대입했으므로 그대로 출력된다.

함수 A() 자체는 A에 인자가 없고 리턴 값이 따로 없으므로 'undefined'가 출력된다. 

 

2. 객체에 속성 추가하기 

먼저 값을 속성으로 넣는 방법이다.

function A(){
    this.name = 'Kim';
}

const a = new A();
console.log(a);
[Running]
A { name: 'Kim' }

'this'를 통하여 name이라는 속성에 'Kim'라는 값을 넣었다.

 

다음은 함수를 속성으로 넣은 경우이다.

function A(){
    this.hello = function(){
        console.log('hello');
    }
}

new A().hello();
[Running] 
hello

A라는 함수에 'hello'를 출력하는 hello() 함수가 속성으로 추가되었고 그대로 출력됨을 알 수 있다.

 

 

'JavaScript' 카테고리의 다른 글

JavaScript 기초(23)_객체(3)  (0) 2021.10.20
JavaScript기초(22)_객체(2)  (0) 2021.10.16
JavaScript기초(20)_함수(6)  (0) 2021.10.14
JavaScript기초(19)_함수(5)  (0) 2021.10.13
JavaScript기초(18)_함수(4)  (0) 2021.10.12

댓글