Javascript

🌟추천🌟this는 도대체 무엇인가

킹king 2021. 2. 20. 17:00
반응형

자바스크립트에서 this는 그 상황마다 가리키는 값이 다름.

 

1. window

2. 자기 자신

3. 앞에 붙은 object

4. ???

 

이렇게 크게 3가지로 나뉨

 


 

1. 일반적인(global scope) 상황에서 this는 window를 가리킴.

this.room = 'window table';
// 콘솔창에 this만 쳐도 자동으로 window가 출력.

 

 

2. object안에서 this는 자기 자신을 가리킴.

this.table = 'window table';

let myRoom = {
    table: 'my table',
};

console.log(this.table) // window table
console.log(myRoom.table) // my table
console.log(this.myRoom.table) // Uncaught TypeError: Cannot read property 'table' of undefined"

 

 

3. method안에서 this는 object를 가리킴.

this.table = 'window table';

let myRoom = {
    table: 'my table',
    cost() {
        console.log(`${this.table} is $250`);
    }
}

myRoom.cost() // my table is $250

 

 

4. function안에서 this는 모름.

this.table = 'window table'

let myRoom = function() {
    console.log(this.table);
}

myRoom() // 'window table'
// use strict 적용 시 Uncaught TypeError: Cannot read property 'table' of undefined"

 

 

5. function안에서 use strict모드일때 this 정상적으로 출력하고 싶을 때

"use strict";

this.table = 'window table';

let myRoom = function() {
	console.log(this.table);
};

myRoom(); // 타입에러
myRoom.call(this) // 'window table'
// myRoom 함수를 쓸껀데 주체는 this라는 말.
// 여기서 this는 window를 가르킴.

 

 

6. inner func에서 use strict모드일때 this 써야할 때

6-1) that = this

'use strict'

this.table = 'window table';

let myRoom = function() {
	let that = this;
	let inner = function() {
		console.log(that.table);
	}
  inner();
};

myRoom.call(this); // window table

 

6-2) 화살표 함수 () =>

'use strict'

this.table = 'window table';

let myRoom = function() {
	let inner = () => {
		console.log(this.table);
	}
  inner();
};

myRoom.call(this);

 

 

7. constructor에서 this는 만들어진 object를 가리킴.

let CreateRoom = function(name) {
    this.table = `${name}s table`
};

let katesRoom = new CreateRoom('kate');

katesRoom.table // kates table

 

 

8. class에서 this는 만들어진 object를 가리킴.

class CreateRoom {
    constructor(name) {
        this.table = `${name}s room`;
    };
    cost() {
        console.log(`${this.table} is $250`);
    };
};

let katesRoom = new CreateRoom('kate');

katesRoom.table; // kates room
katesRoom.cost(); // kates room is $250

 

 

youtu.be/NV9sHLX-jZU

모든 게시물(특히 과거 게시물)은 잘못된 방법으로 처리한것을 좋다고 써놨을 수 있습니다. 참고만 하시고 틀린게 있다면 댓글 남겨주세요~