[자바스크립트]this 키워드

트릴로니·2022년 7월 22일

자바스크립트

목록 보기
20/31

this?

this is the object that the function is a property of

어떤 객체가 있고 객체에 함수 프로퍼티가 있다. 함수에서 this는 그 함수가 있는 객체를 가리킨다.

obj.someFunc(this)

function a() {
	console.log(this)
}
a()
//window.a()
  • 함수 a는 Window 객체의 프로퍼티이다. 그래서 this는 Window 객체를 가리킨다.
function b() {
	'use strict'
    console.log(this)
}
b()
//undefined
  • 'use strict': use strict 모드에서는 함수의 this가 Window 객체를 가리키지 못하도록 한다.
  • ES6 모듈은 'use strict'를 기본으로 한다.
const obj = {
	name: 'Billy',
    sing: function() {
    	return 'lalala' + ...
    }
}

obj 객체의 함수 sing은 name프로퍼티 값을 가지고 오고 싶으면 어떻게 해야될까?

  • 이런 경우 this 키워드를 쓰면 된다.
  • this의 정의를 다시 복기해 보면 this는 어떤 함수가 프로퍼티로 있는 객체이다. 즉 sing함수를 프로퍼티로 가지고 있는 obj를 가리킨다.
const obj = {
	name: 'Billy',
    sing: function() {
    	return 'lalala' + this.name
    }
}
obj.sing()
obj.sing()

this는 '.'을 기준으로 왼쪽을 가리킨다

const obj = {
	name: 'Billy',
    sing() {
    	return 'lalala' + this.name
    },
    singAgain() {
    	return 'lalala' + this.name + '!'
    }
}
obj.singAgain()
  • 위 코드에서 sing함수와 singAgain의 코드가 중복된 것을 볼 수 있다. 이를 피하기 위해 아래와 같이 쓸 수 있다.
const obj = {
	name: 'Billy',
    sing() {
    	return 'lalala' + this.name
    },
    singAgain() {
    	return this.sing() + '!'
    }
}
obj.singAgain()

this의 2가지 장점

  1. 함수가 객체의 다른 프로퍼티를 쓸 수 있게된다.

  2. 같은 코드를 다중의 객체에서 쓸 수 있다.

function importantPerson() {
	cosnole.log(this.name)
   	//this = Window 객체
}
importantPerson()
//window.importantPerson()

const name ='Sunny'
const obj1 = {
	name : 'Cassy',
    importantPersone: importantPerson()
    //this.name: 'Cassy'
}
const obj2 = {
	name : 'Jacob',
    importantPersone: importantPerson()
    //this.name: 'Jacob'
}

Dynamic Scope vs Lexical Scope

const a = function() {
	console.log('a', this)
    const b = function () {
    	console.log('b', this)
        const c = {
        	hi: function() {
            	console.log('c', this)
            }
        }
        c.hi()
    }
    b()
}

// a Window
// b Window     Window.a(b()) : this는 '.'을 기준으로 왼쪽
// c {hi: f}
  • 렉시컬 스코프: 함수를 어디서 호출하는지가 아니라 어디서 선언하였는지에 따라 결정된다
const obj = {
	name: 'Billy',
    sing() {
    	console.log('a', this);
        var anothreFunc = functino() {
        	console.log('b', this)
        }
        anotherFunc()
    }
}
obj.sing()
// a {name: 'Billy', sing: f}
// b Window
  • this 키워드는 렉시컬 스코프되지 않는다.
  • 즉 this는 어디서 선언하였는 지에 따라 결정되는 것이 아니라, 어디서 호출되는 지에 따라 결정된다.(dynamic scope)
  • obj객체는 어떤 함수도 호출하지 않는다.
  • the sing function did in js this keyword defaults to the window object in here

solution

  • 화살표 함수 사용
  • 화살표 함수는 this 키워드는 lexical하도록 만든다.
const obj = {
	name: 'Billy',
    sing() {
    	console.log('a', this);
        var anothreFunc = () => {
        	console.log('b', this)
        }
        anotherFunc()
    }
}
//obj.sing()
// a {name: 'Billy', sing: f}
// b {name: 'Billy', sing: f}

0개의 댓글