Language/JavaScript

[JavaScript] 객체지향, new 그리고 this

jaewpark 2021. 10. 9. 20:04

Java와 비슷한 거 같으나 전혀 다른 객체지향을 추구

서로 연관되어 있는 변수와 메소드를 객체에 담아낸다.

 

var person = {} // {} 는 object == 객체 (비어있는 상자))

peeson.name = 'egoing'; // name 이라는 property (속성)를 객체에 담고 그 내용은 'egoing'

person.introduce =fuction() { // property에 담겨있는 게 함수라면, 메소드

    return 'My name is '+this.name;

}

document.write(person.introduce());

 

위와 같은 객체는 아래 코드처럼 사용이 가능하다.

1
2
3
4
5
6
7
var person = {
    'name' : 'egoing',
    'introduce' : function(){
        return 'My name is '+this.name;
    }
}
document.write(person.introduce());
cs

생성자 new

 

fuction person() {}

var p = new person(); // 함수에 new (생성자) 를 붙이게 되면 객체가 생성

 

그 위에서 설명 되었던 코드로 여러 person 을 기록 한다고 하면 introduce 와 같은 함수가 중복

1
2
3
4
5
6
7
8
9
10
11
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());
cs

위와 같은 형태로 바꿀 수 있다.

 


 

this

 

실행 컨텍스트(global, function 또는 eval)의 프로퍼티는 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값이든 될 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
cs

 

코드를 보게되면 그 함수가 누구의 소속이냐에 따라 this는 달라진다.

this