Notice
Recent Posts
Recent Comments
Link
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
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
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[JavaScript] ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์™€ ์ผ๋ฐ˜ ํ•จ์ˆ˜์˜ ์ฐจ์ด ๋ณธ๋ฌธ

๐Ÿง‘‍๐Ÿ’ป Web/JavaScript

[JavaScript] ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์™€ ์ผ๋ฐ˜ ํ•จ์ˆ˜์˜ ์ฐจ์ด

Lennon 2022. 6. 3. 15:39
728x90
๋ฐ˜์‘ํ˜•

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ ์ผ๋ฐ˜ ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ this์— ๋ฐ”์ธ๋”ฉํ•  ๊ฐ์ฒด๊ฐ€ ๋™์ ์œผ๋กœ ๊ฒฐ์ •๋œ๋‹ค.

์•„๋ž˜ ํ•จ์ˆ˜๊ฐ€ ์–ด๋–ป๊ฒŒ ์‹คํ–‰๋  ์ง€ ์˜ˆ์ƒํ•ด๋ณด์ž.

const obj = {
    name: 'minho',
    
    intro: function() {
    	console.log(this.name)
        
        setTimeout(function() {
        	console.log(this.name)
        }, 1000)
    }
}

obj.intro()

๋…ผ๋ฆฌ์ ์œผ๋กœ ์ƒ๊ฐํ•ด๋ณด๋ฉด ๋‹น์—ฐํžˆ minho๊ฐ€ ๋‘ ๋ฒˆ ๋œฐ๊ฑฐ๋ผ ์ƒ๊ฐํ•œ๋‹ค.
๊ทธ๋Ÿฌ๋‚˜ ๋‘ ๋ฒˆ์งธ console.log๋Š” undefined๊ฐ€ ๋œจ๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด์œ ๋Š” ๋ฌด์—‡์ผ๊นŒ?

 

setTimeout ๋‚ด๋ถ€์˜ this๋Š” window๋ฅผ ๊ฐ€๋ฅดํ‚ค๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
ํ•ด๋‹น ๋ฌธ์ œ๋ฅผ ์•„๋ž˜ ์ฝ”๋“œ์™€ ๊ฐ™์ด bind, call, apply๋ฅผ ํ†ตํ•ด ์–ด๋””์— ๋ฐ”์ธ๋”ฉํ• ์ง€ ์ •ํ•ด์ค„ ์ˆ˜ ์žˆ์ง€๋งŒ ๋” ํŽธ๋ฆฌํ•œ ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.

const obj = {
	name: 'minho',
    
    intro: function() {
    	console.log(this.name)
        
        setTimeout(function() {
        	console.log(this.name)
        }.bind(this), 1000)
    }
}

obj.intro()

 

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜

const obj = {
	name: 'minho',
    
    intro: function() {
    	console.log(this.name)
        
        setTimeout(() => {
        	console.log(this.name)
        }, 1000)
    }
}

obj.intro()

์˜ˆ์ƒ๊ณผ ๊ฐ™์ด minho๊ฐ€ ๋‘ ๋ฒˆ ๋œจ๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋Š” ์ผ๋ฐ˜ ํ•จ์ˆ˜์™€ ๋‹ฌ๋ฆฌ ์–ธ์ œ๋‚˜ ์ƒ์œ„ ์Šค์ฝ”ํ”„์˜ this๋ฅผ ๊ฐ€๋ฅดํ‚ค๊ธฐ ๋•Œ๋ฌธ์— ์ƒ๊ฐํ•˜์ง€ ๋ชปํ•œ ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๊ทธ๋Ÿฌ๋‚˜ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

 

๋ฉ”์†Œ๋“œ๋ฅผ ์ •์˜ํ•  ๋•Œ 

const obj = {
    name: 'minho',
    intro: () => console.log(`Hi my name is ${this.name}`)
};

obj.intro();

์‹ค์ œ ํ˜ธ์ถœ์„ ํ™•์ธํ•ด๋ณด๋ฉด 'Hi my name is undefined` ๊ฐ€ ๋œจ๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

๋‹น์—ฐํ•˜๋‹ค. ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•œ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฅดํ‚ค๋Š” ๊ฒŒ ์•„๋‹ˆ๋ผ ์ €๊ธฐ์„œ์˜ this๋Š” ์ƒ์œ„ ์ปจํƒ์ŠคํŠธ์ธ ์ „์—ญ ๊ฐ์ฒด์ผ ์ˆ˜ ๋ฐ–์— ์—†๋‹ค.

const obj = {
    name: 'minho',
    intro() {
    	console.log(`Hi my name is ${this.name}`)
    }
};

obj.intro();

๋ฉ”์„œ๋“œ๋Š” ์ •์˜ํ•  ๋•Œ๋Š” ์ถ•์•ฝ ๋ฉ”์†Œ๋“œ ํ‘œํ˜„์„ ์‚ฌ์šฉํ•˜์ž. 

 

 

๋ฌธ์ œ์ ๋“ค์„ ์ฃผ์˜ํ•˜๋ฉฐ ํ™”์‚ดํ‘œํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ž!

728x90
๋ฐ˜์‘ํ˜•
Comments