Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
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
more
Archives
Today
Total
관리 메뉴

어리바리 신입 개발자의 얼렁뚱땅 개발 기록 ✨

23.04.16 / 객체를 생성하는 방법과 콘솔 출력 & 프로토타입 본문

Front - end/JS

23.04.16 / 객체를 생성하는 방법과 콘솔 출력 & 프로토타입

낫쏘링 2023. 4. 16. 03:14
728x90

[ 1.객체 생성 방법 ]

1. 객체 리터럴 방식
const cat = {
    name: '삼색이',
    age: 3,
    sayMeow: function () {
        console.log(`${this.name}는 ${this.age}살`);
    }
};

// 객체 내에 속성과 메서드를 선언할 때 선언 키워드(var,let,const 사용하지 않는다.)
// 속성과 메서드를 선언할 때는 this 사용하지 않음. 
// 객체 내의 속성이나 메서드를 사용하려면 this 사용해야 한다.



2-1. 생성자 함수 사용 (자바스크립트 내장 함수인 Object() 생성자 함수)

const cat = new Object();

cat.name = '삼색이';
cat.age = 3;
cat.sayMeow = function () {
    console.log(`${this.name}는 ${this.age}살`);
    return this.name;
}



2-2. 생성자 함수 사용 

function Animal(name, age) {
    this.name = name;
    this.age = age;
    this.sayIntro = function () {
        console.log(`${this.name}는 ${this.age}살`);
        return this.name;
    }
}

const cat = new Animal('삼색이', 3);
const dog = new Animal('바둑이', 5);

// 생성자 함수를 이용하면 한 번의 함수 선언으로 여러 객체를 생성할 수 있다.
// cat 객체는 Animal 객체로 부터 상속 받은 자식 객체라고 볼 수 있다.
// 생성자 함수 내의 속성과 메서드는 this를 붙여야 한다.
// this를 붙이지 않고 선언 키워드(var,let,const)로 선언은 가능하지만 스코프 때문에 블록 밖에서 사용 불가능

[ 2. prototype 프로토타입 ]

- 다른 객체의 원형이 되는 객체(Object 객체)로 모든 객체는 프로토 타입 객체에 접근할 수 있다.
   즉, 모든 객체의 부모 객체라고 볼 수 있다. (생성자 함수에 의해 생성된 객체 뿐 아니라 모든 객체)
- 생성자 함수를 통해 생성된 객체는 생성자 함수의 모든 프로토타입(속성과 메서드)을 상속 받는다.

생성자 함수를 통해 한 번의 선언으로 여러 객체를 생성할 수 있지만,
객체를 생성할 때마다 객체의 속성과 메서드가 저장되는 공간이 메모리에 할당되기 때문에 메모리의 효율성이 떨어진다.
생성자 함수로 만들어진 모든 객체는 완전히 동일한 기능을 하는 메서드를 가지고 있다.
따라서 동일한 기능을 하는 부분들은 선언시 한 번만 메모리에 할당되도록 할 수 있도록 
프로토타입으로 선언할 수 있다. (속성의 경우 객체 마다 값이 달라지기 때문에 프로토타입으로 선언하지 않는다. - 값이 같을 경우 가능)
function Animal(name, age) {
    this.name = name;
    this.age = age;
    Animal.prototype.sayIntro = function () {
        console.log(`${this.name}는 ${this.age}살`);
        return this.name;
    }
};

const cat = new Animal('삼색이', 3);
const dog = new Animal('바둑이', 5);
// 객체 cat와 dog의 프로토타입은 Animal.prototype 이다.

 

[ 3.객체 콘솔 출력 ]

1. console.log( parameter );

// 객체 리터럴 & Object() 생성자 함수로 객체 생성

console.log(cat);

▾{name: '삼색이', age: 3, sayMeow: ƒ}
	age : 3
	name : "삼색이"
	▸sayMeow : ƒ ()
	▸[[Prototype]] : Object
    
// cat 객체의 속성과 메서드 출력

---------------------------------------------------------------------------

// 생성자 함수로 객체 생성

console.log(cat);

▾Animal {name: '삼색이', age: 3, sayIntro: ƒ}
	age : 3
	name : "삼색이"
	▸sayMeow : ƒ ()
	▸[[Prototype]] : Object
    
// 객체 리터럴 방식과 Object() 생성자 함수로 선언했을 때와 다르게
// 중괄호 앞에 상속 받은 부모 객체인 Animal이 함께 출력된다.

---------------------------------------------------------------------------

// 생성자 함수로 객체 생성

console.log(Animal);

ƒ Animal(name, age) {
            this.name = name;
            this.age = age;
            this.sayIntro = function () {
                console.log(`${this.name}는 ${this.age}살`);
                return this.name;
            }
}

// 반면 Animal은 객체가 아닌 함수이기 때문에 Animal을 호출하면 함수가 출력된다.
// 자바스크립트에서 함수, 배열, 객체는 모두 객체 취급한다.
// 때문에 Animal()은 객체 취급하지만, 엄연히 함수기 때문에 함수 형태로 출력된다.

---------------------------------------------------------------------------

// 생성자 함수로 객체 생성 후 프로토타입으로 메서드 선언

console.log(cat);

▾Animal {name: '삼색이', age: 3}
	age : 3
	name : "삼색이"
	▾[[Prototype]] : Object
        ▸sayIntro : ƒ ()
        ▸constructor : ƒ Animal(name, age)
        ▸[[Prototype]] : Object
        
// 생성자 함수로 객체를 생성했기 때문에 Animal 함수를 참조하고 있는 것을 알 수 있다.
// 하지만 생성자 함수로 객체를 생성 후 객체 내에 this로 메서드를 선언했을 때와 다르게
// sayIntro() 메서드가 객체 내에 속하지 않고 Prototype : Object에 속하는 것을 알 수 있다.

 

2. console.log( { parameter } );  -  객체 출력

// 객체 리터럴 & Object() 생성자 함수로 객체 생성

console.log({ cat }); 

▾{cat: {…}}
	▸cat: {name: '삼색이', age: 3, sayMeow: ƒ}
	▸[[Prototype]]: Object
    
// cat 객체 출력

---------------------------------------------------------------------------

// 생성자 함수로 객체 생성

console.log({ cat });

▾{cat: Animal}
	▸cat: Animal {name: '삼색이', age: 3, sayMeow: ƒ}
	▸[[Prototype]]: Object
    
// 객체 리터럴 방식과 Object() 생성자 함수를 사용했을 때와 다르게
// cat 객체가 Animal 함수를 참조하고 있음을 알 수 있다.
    
---------------------------------------------------------------------------

// 생성자 함수로 객체 생성

console.log({ Animal });

▾{Animal: ƒ}
	▸Animal : ƒ Animal(name, age)
	▸[[Prototype]] : Object

// Animal은 함수지만 객체 취급하기 때문에 객체를 출력하는 코드를 넣었을때도 출력된다.



3. cat.sayMeow(); / cat.sayIntro();

// 객체 리터럴 & Object() 생성자 함수로 객체 생성

cat.sayMeow();

삼색이는 3살

// cat 객체를 찾아가서 sayMeow() 메서드를 호출한다.
// 콘솔에 출력하는 코드 없이 호출만 했기 때문에
// sayMeow 메서드 내에서 콘솔 코드에 입력된 문자열만 출력되고 return 값은 출력되지 않는다.

---------------------------------------------------------------------------

// 생성자 함수로 객체 생성

cat.sayIntro();
dog.sayIntro();

삼색이는 3살
바둑이는 5살

// cat 객체와 dog 객체를 를 찾아가서 sayIntro() 메서드를 호출한다.
// 콘솔에 출력하는 코드 없이 호출만 했기 때문에
// sayIntro 메서드 내에서 콘솔 코드에 입력된 문자열만 출력되고 return 값은 출력되지 않는다.
// 생성자 함수를 사용하면 한 번 함수를 선언해서 여러 객체를 만들 수 있다.



4.  console.log(cat.sayIntro);

console.log(cat.sayMeow());

삼색이는 3살
삼색이

// cat 객체를 찾아가서 sayMeow 메서드를 호출, 출력한다.
// 원래 콘솔 코드에 입력되어있던 문자열 '삼색이는 3살'과
// 콘솔 없이 리턴된 리턴 값 this.name의 값인 '삼색이'가 출력된다.

---------------------------------------------------------------------------

console.log(cat.sayIntro());
console.log(dog.sayIntro());

삼색이는 3살
삼색이

바둑이는 5살
바둑이

// cat 객체와 dog 객체를 를 찾아가서 sayIntro() 메서드를 호출한다.
// 콘솔에 출력하는 코드 없이 호출만 했기 때문에
// sayIntro 메서드 내에서 콘솔 코드에 입력된 문자열만 출력되고 return 값은 출력되지 않는다.
// 생성자 함수를 사용하면 한 번 함수를 선언해서 여러 객체를 만들 수 있다.
// 원래 콘솔 코드에 입력되어있던 문자열 '삼색이는 3살'과
// 콘솔 없이 리턴된 리턴 값 this.name의 값인 '삼색이'가 출력된다.

 

[ 4. 속성 또는 메서드 추가 ]

1. 객체
function Animal(name, age) {
    this.name = name;
    this.age = age;
    this.sayIntro = function () {
        console.log(`${this.name}는 ${this.age}살`);
        return this.name;
    }
}

const cat = new Animal('삼색이', 3);

cat.vaccine = 'yes';
cat.sayVac = function () {
	console.log(`백신 접종 여부 : ${this.vaccine}`);
    return this.vaccine;

const dog = new Animal('바둑이', 5);

// vaccine이라는 속성과 sayVac이라는 메서드는 cat 객체 내에만 추가 됐다.
// 같은 Animal 함수를 상속 받았어도 나중에 추가된 속성과 메서드는 객체 마다 다르다.

console.log(cat);
// Animal {name: '삼색이', age: 3, vaccine: 'yes', sayIntro: ƒ, sayVac: ƒ}

console.log(dog);
// Animal {name: '바둑이', age: 5, sayIntro: ƒ}


2. 프로토타입
function Animal(name, age) {
    this.name = name;
    this.age = age;
    Animal.prototype.sayIntro = function () {
        console.log(`${this.name}는 ${this.age}살`);
        return this.name;
    }
}

const cat = new Animal('삼색이', 3);

Animal.prototype.vaccine = 'yes';
Animal.prototype.sayVac = function () {
    console.log(`백신 접종 여부 : ${this.vaccine}`);
    return this.vaccine;
}

const dog = new Animal('바둑이', 5);
728x90