๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • What would life be If we had no courage to attemp anything?
Language/JavaScript

JavaScript - this

by DevIseo 2022. 5. 2.

this - "์ž๊ธฐ์ฐธ์กฐ๋ณ€์ˆ˜"

์ •์˜

  • ๋‚ด๊ฐ€ ์–ด๋–ป๊ฒŒ ๋ถˆ๋ฆฌ๋Š๋ƒ์— ๋”ฐ๋ผ ๋ฐ”์ธ๋”ฉ ๋˜๋Š” ๊ฒƒ.

๋ชฉ์ 

  • "๊ฐ์ฒด"์—์„œ "๋‚ด"๊ฐ€ ํ”„๋กœํผํ‹ฐ๋‚˜ ๋ฉ”์„œ๋“œ๋ฅผ ์ฐธ์กฐํ•˜๊ธฐ ์œ„ํ•ด

"์–ด๋””์„œ" "์–ด๋–ป๊ฒŒ" ๋ถ€๋ฅด๋Š๋ƒ์— ๋”ฐ๋ผ this๋Š” ๋‹ฌ๋ผ์ง„๋‹ค!

  • ์ผ๋ฐ˜ ํ•จ์ˆ˜๋กœ ํ˜ธ์ถœ ๋˜์—ˆ์„ ๋•Œ -> **์ „์—ญ ๊ฐ์ฒด**
    • ํ•จ์ˆ˜() -> window
    function test(){
        console.log(this)
    }
    test()
    Window {0: global, window: Window, self: Window, document: document, name: '', location: Locationโ€ฆ}
  • ๋ฉ”์„œ๋“œ๋กœ ํ˜ธ์ถœ ๋˜์—ˆ์„ ๋•Œ -> **"๊ทธ" ๋ฉ”์„œ๋“œ๋ฅผ ๋ณด์œ ํ•œ ๊ฐ์ฒด **
    • ๊ฐ์ฒด.๋ฉ”์„œ๋“œ() ->๊ฐ์ฒด
    const obj = {}
    
    const obj = {
        test : function(){
            console.log(this)
        }
    }
    
    obj.test()
{test: ฦ’}
	test: ฦ’ ()
		arguments: null
		caller: null
		length: 0
		name: "test"
		prototype: {constructor: ฦ’}
		[[FunctionLocation]]: VM4936:2
		[[Prototype]]: ฦ’ ()
		[[Scopes]]: Scopes[2]
	[[Prototype]]: Object
  • ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋กœ ํ˜ธ์ถœ ๋˜์—ˆ์„ ๋•Œ -> **"๋ฏธ๋ž˜"์— ์ƒ์„ฑ๋  "์ธ์Šคํ„ด์Šค"** -> ๊ฐ์ฒด
    Teacher {name: 'iseo'}
    	name: "iseo"
    	[[Prototype]]: Object
    		constructor: ฦ’ Teacher(name)
    		[[Prototype]]: Object
    //cf.
    const person2 = Teacher('iseo')
    //์ด๋ ‡๊ฒŒ ๋„ฃ์œผ๋ฉด(newํ‚ค์›Œ๋“œ ๋นผ๋จน์œผ๋ฉด) ์ผ๋ฐ˜ ํ•จ์ˆ˜ ํ˜ธ์ถœ๊ณผ ๊ฐ™์•„์ ธ ์ „์—ญ์ธ window์— Teacher : 'iseo'๊ฐ€ ๋“ค์–ด๊ฐ€๋ฒ„๋ฆผ....
    //๊ฒฐ๋ก  : ์ด ๊ฒฝ์šฐ์˜ this๋Š” window์— ๋ฐ”์ธ๋”ฉ ๋˜์–ด๋ฒ„๋ฆฐ๋‹ค!!
  • function Teacher(name){ this.name = name //"๋ฏธ๋ž˜"์— ์ƒ์„ฑ๋  "์ธ์Šคํ„ด์Šค" } const person = new Teacher('iseo') person
  • apply/call/bind๋กœ "๊ฐ„์ ‘"ํ˜ธ์ถœ ๋˜์—ˆ์„ ๋•Œ

|function ํ‚ค์›Œ๋“œ์™€ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ์ฐจ์ด

  • this.radiuses๋Š” ๋ฉ”์„œ๋“œ(๊ฐ์ฒด.๋ฉ”์„œ๋“œ๋ช…()์œผ๋กœ ํ˜ธ์ถœ ๊ฐ€๋Šฅ) ์†Œ์†์ด๊ธฐ ๋•Œ๋ฌธ์— ์ •์ƒ์ ์œผ๋กœ ์ ‘๊ทผ ๊ฐ€๋Šฅ
  • forEach์˜ ์ฝœ๋ฐฑํ•จ์ˆ˜์˜ ๊ฒฝ์šฐ ๋ฉ”์„œ๋“œ๊ฐ€ ์•„๋‹˜ (๊ฐ์ฒด.๋ฉ”์„œ๋“œ๋ช…()์œผ๋กœ ํ˜ธ์ถœ ๋ถˆ๊ฐ€๋Šฅ)
  • ๋•Œ๋ฌธ์— ์ฝœ๋ฐฑํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ this๋Š” window๊ฐ€ ๋˜์–ด this.PI๋Š” ์ •์ƒ์ ์œผ๋กœ ์ ‘๊ทผ ๋ถˆ๊ฐ€๋Šฅ
  • ์ด ์ฝœ๋ฐฑํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ this.PI์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ ํ•จ์ˆ˜๊ฐ์ฒด.bind(this) ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉ.
  • ์ด ๋ฒˆ๊ฑฐ๋กœ์šด bind ๊ณผ์ •์„ ์—†์•ค ๊ฒƒ์ด ํ™”์‚ดํ‘œ ํ•จ์ˆ˜

Summary

  • ํ•จ์ˆ˜ ๋‚ด๋ถ€์— this ํ‚ค์›Œ๋“œ๊ฐ€ ์กด์žฌํ•  ๊ฒฝ์šฐ
    • ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์™€ function ํ‚ค์›Œ๋“œ๋กœ ์„ ์–ธํ•œ ํ•จ์ˆ˜๊ฐ€ ๋‹ค๋ฅด๊ฒŒ ๋™์ž‘
  • ํ•จ์ˆ˜ ๋‚ด๋ถ€์— this ํ‚ค์›Œ๋“œ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ
    • ์™„์ „ํžˆ ๋™์ผํ•˜๊ฒŒ ๋™์ž‘

์ฐธ๊ณ ํ•˜๊ธฐ ์ข‹์€ ๋ธ”๋กœ๊ทธ ๊ธ€ ๋งํฌ