Try to be the expert.

Ainsetin's Hacking & PS & Math

2021 1人 1 Project

1인 1프로젝트 : 6일차 (객체와 this의 역할)

Ainsetin 2021. 3. 30. 08:36

이번에는 javascript의 큰 특징인 객체의 this에 대해서 공부하였다.

 

1
2
3
4
5
6
7
8
9
let user = {
  name"John",
  age: 30,
  
  // 메서드 선언
  sayHi(){
    alert(this.name);
  }
}
cs

 

객체는 다음과 같이 {}와 key - value 형태로 선언할 수 있다.

객체 안에는 위와 같이 메서드를 선언할 수도 있다. 여기서 메서드란, 객체 property 안에 할당된 함수를 의미한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
let user = {
  name"John",
  age: 30,
  
  // 메서드 선언
  sayHi(){
    alert(this.name);
  }
}
 
let admin = user;
admin.sayHi();
cs

 

다음과 같이 다른 let 변수에 복사하는 식으로 객체를 복사할 수도 있다.

12번째줄과 같이 변수에 .을 붙여 객체 안에 있는 key 값을 참조할 수 있다는 것이 객체의 특징이라고 할 수 있다.

 

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
let user = {
  name"John"
};
 
let admin = {
  name"Admin"
};
 
function sayHi(){
  alert(this.name);
}
 
user.f = sayHi;
admin.f = sayHi;
 
user.f()
admin.f()
 
admin['f']();
 
function hello(){
  alert(this);
}
 
hello();
cs

 

위와 같이 user와 admin 변수에 객체를 따로 선언하고,

this.name (??) 을 alert하는 함수를 각각의 f라는 key에 복사하였다.

정확히 말하자면, f라는 메서드를 선언한 것으로 보면 된다.

 

놀랍게도 오류를 내지 않고 둘 다 John과 Admin을 잘 출력한다. 왜그럴까?

this라는 것은 쉽게 말해 자기 자신, 즉 현 객체를 가리킨다는 것을 알 수 있다. 객체를 가리키기 때문에, .으로 key값이나 메서드를 참조할 수 있는 것이다.

 

19번째 줄을 실행해도 Admin이 잘 나온다. 즉, 메서드도 key - value 형태에 ()을 붙여 호출할 수 있다는 것이다.

그렇다면, this 자체를 출력하면 어떤 값이 나올까?

 

??

도대체 [object Window]는 뭘까...

이 결과는 사용자 객체에 포함되지 않은 함수의 this 값을 확인한 결과였다.

즉, javascript에는 전역 객체가 존재하는 것을 알 수 있다.

더 자세히 보니, use strict 모드를 사용하지 않으면 이 문법은 오류를 내지 않는다고 한다.

 

다음 코드는 this 실습을 위한 코드이다.

 

- 유저를 만들어 자기 자신 객체를 호출해 이름을 가져오는 실습 코드

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
32
33
34
35
function makeUser(){
  return {
    name"John",
    ref: this
  };
};
 
let user = makeUser();
 
alert( user.ref.name );
alert(user.name);
 
 
function makeUser2(){
  return this;
}
 
alert(makeUser2().name);
 
 
 
// user.ref() is method, this == returned object
function makeUser3(){
  return {
    name"John",
    ref() {
      return this;
    }
  };
};
 
let user = makeUser3();
 
alert(user.ref()); // return한 object (name, ref())
alert(user.ref().name); // 그 object에서 name을 가져오므로 john 
cs

 

- this를 활용한 덧셈뺄셈 계산기 실습코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let calculator = {
  read() {
    a = +prompt("첫번째 값을 입력해주세요.");
    b = +prompt("두번째 값을 입력해주세요.");
    this.a=a;
    this.b=b;
  },
  sum() {
    return this.a+this.b;
    //return Number(this.a)+Number(this.b);
  },
  mul() {
    return this.a*this.b;
  }
}
 
calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );
cs