Study/JavaScript

자바스크립트의 객체지향

토기발 2022. 8. 26. 21:27

생활코딩 자바스크립트 강의를 듣고 정리한 포스팅이다.

 

 

 

 

var person = {}

{} 로 빈 그릇(오브젝트, 객체)를 생성한다.

var person = {}
person.name = 'egoing';
person.introduce = function(){
    return 'My name is '+this.name;
}
document.write(person.introduce());

객체 내의 변수를 프로퍼티라고 한다.(name, introduce)

프로퍼티에 담긴 함수는 메소드라고 한다. (function(){})

위 함수에서 this는 해당 함수가 속해있는 객체({})에 담겨있는 객체(name=egoing)이다.

 

var person = {
    'name' : 'egoing',
    'introduce' : function(){
        return 'My name is '+this.name;
    }
}
document.write(person.introduce());

객체를 만드는 과정이 분산되어 있어서 통합하였다.

그런데 만약 사람이 10명이 있다면 같은 코드를 10번 반복하고 name을 바꿔야 한다면 너무 중복이 많고 유지보수가 어려운 코드가 된다.

이럴 때 사용하는 것이 생성자다.

 

생성자

function Person(){}
var p = new Person();

함수에 new를 붙여서 생성자를 만들었다.

생성자(constructor)는 객체를 만드는 역할을 하는 함수다. 자바스크립트에서 함수는 재사용 가능한 로직의 묶음이 아니라 객체를 만드는 창조자라고 할 수 있다.

 

function Person(name){
    this.name = name;
    this.introduce = function(){
        return 'My name is '+this.name; 
    }   
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
 
var p2 = new Person('leezche');
document.write(p2.introduce());

생성자를 사용하면 코드를 재사용해서 쓸 수 있게 된다.

 

 

전역객체

 

 window. 를 생략한 func();도 동일하게 실행된다. 

모든 전역변수와 함수는 사실 window 객체의 프로퍼티다. 객체를 명시하지 않으면 암시적으로 window의 프로퍼티로 간주된다. 

자바스크립트에서 모든 객체는 기본적으로 전역객체의 프로퍼티임을 알 수 있다. 

 

 

this

함수 내에서 함수 호출 맥락(context)를 의미한다. 

함수를 어떻게 호출하느냐에 따라 가리키는 대상이 달라진다는 뜻이다.

function func(){
    if(window === this){
        document.write("window === this");
    }
}
func();

함수를 호출했을 때 this는 전역객체인 window와 같다.

 

var o = {
    func : function(){
        if(o === this){
            document.write("o === this");
        }
    }
}
o.func();

메소드에서 this는 그 객체를 가리킨다.

 

 

var funcThis = null; 
 
function Func(){
    funcThis = this; //var가 붙지 않아서 전역변수를 가리킴
}
var o1 = Func();
if(funcThis === window){ 
    document.write('window <br />');
}
 
var o2 = new Func(); //빈객체를 만들고 생성자 안에서 this가 된다.
if(funcThis === o2){
    document.write('o2 <br />');
}

결과는 

window

o2

이다.

생성자는 빈 객체를 만든다. 그리고 이 객체내에서 this는 만들어진 객체를 가리킨다. 

 

 

 

var o = {}
var p = {}
function func(){
    switch(this){
        case o:
            document.write('o<br />');
            break;
        case p:
            document.write('p<br />');
            break;
        case window:
            document.write('window<br />');
            break;          
    }
}
func();
func.apply(o);
func.apply(p);

apply와 call로 this의 값을 제어할 수 있다. 

'Study > JavaScript' 카테고리의 다른 글

[JavaScript] JS파일 코드 변경사항이 반영되지 않는 문제  (0) 2023.07.08
자바스크립트의 객체지향 - 상속  (0) 2022.08.28
값으로서의 함수와 콜백  (0) 2022.08.25
유효범위(Scope)  (0) 2022.08.25
jQuery  (0) 2022.08.24