function defaultPrice(price = 4) {
return price
}
defaultParameter() // 4;
defaultParameter(8) // 8;
๋งค๊ฐ๋ณ์๋ ๋ณ์๋ค. price๋ 4๋ผ๋ ๊ธฐ๋ณธ๊ฐ์ ๊ฐ์ง๊ณ ์๊ณ , ์ ํจ์ scope์์ ์ฐ์ด๋ ๊ฐ์ด๋ค.
scope๋ ํจ์๋ฅผ ์ ์ธํ ๋ ์๊ธด๋ค.
์ ์ธํ๋ ์๊ฐ, ํจ์ ๋ด๋ถ์ ๋ณ์๋ ์๊ธฐ ์ค์ฝํ๋ถํฐ ๊ฐ์ฅ ๊ฐ๊น์ด ๊ณณ(์์ ๋ฒ์)์ ์๋ ๋ณ์๋ฅผ ๊ณ์ ์ฐธ์กฐํ๊ฒ ๋๋ค.
์ค์ฝํ๋ฅผ ๊ตฌ๋ถํ๋ ๊ฑธ ์๋ฌํด์ผ๊ฒ ๋ค. ์ด๋ ๊ณณ์์๋ ์ ์ฐ์ด๊ณ ์ด๋ ๊ณณ์์ ์ฐ์ด๊ณ ๋ด๋ถ ์ค์ฝํ์์ ๋ณ์๋ฅผ ์ฌํ ๋นํ๋ฉด ์ธ๋ถ์ ์๋ ๋ณ์๊ฐ ์ฌํ ๋น๋๋ค๋ ๊ฑธ ์กฐ์ฌํด์ผ๊ฒ ๋ค.
ํด๋ก์ ๋ ํจ์์ ํจ์๊ฐ ์ ์ธ๋ ์ดํ์ ํ๊ฒฝ์ ์กฐํฉ์ด๋ค. ์ด ํ๊ฒฝ์ ํด๋ก์ ๊ฐ ์์ฑ๋ ์์ ์ ์ ํจ ๋ฒ์ ๋ด์ ์๋ ๋ชจ๋ ์ง์ญ ๋ณ์๋ก ๊ตฌ์ฑ๋๋ค.
multipeBy3๊ณผ multipleBy5 ํจ์๋ ํด๋ก์ ํจ์๋ค. ํจ์์ ์ ์ ๋ณธ๋ฌธ์ ๊ณต์ ํ์ง๋ง ์๋ก ๋ค๋ฅธ ์ดํ(๋งฅ๋ฝ)์ ํ๊ฒฝ์ ์ ์ฅํ๋ค. multipleBy3์ multipleByAmount ํ๋ผ๋ฏธํฐ๋ฅผ 3์ผ๋ก ํ๊ฒฝ์ ์ธํ
ํด ๋์ ์ํ๋ค. ๋ง์ฐฌ๊ฐ์ง๋ก MultipleBy5์ multipleByAmount ํ๋ผ๋ฏธ๋๋ฅผ 5๋ก ํ๊ฒฝ์ ์ธํ
ํ ์ํ๋ค.
const nums1 = [1, 2, 3];
const nums2 = [1 ,2, 3];
nums1 === nums2 // false; nums1๊ณผ nums2 ์๋ก ์ฃผ์๊ฐ์ด ๋ค๋ฅด๋ค.
[1, 2, 3] // ๋ฐ์ดํฐ๊ฐ heap์ ์ ์ฅ๋์ง๋ง ๋ณ์ ํ ๋น์ด ๋์ง ์์ ์ฃผ์๋ ์ด๋์๋ ์ ์ฅ๋์ง ์๋๋ค.
nums1 === [1, 2, 3]; // false; ์๋ก ๋ค๋ฅธ ์ฃผ์์ ์ ์ฅ๋์๊ธฐ ๋๋ฌธ์ false๊ฐ ๋๋ค.
const cal = {
prop:14,
func: function() {
return this.prop
}
}
console.log(cal.func()); // 14;
this๋ class ํค์๋๊ฐ ์๋ ์์ ์ฐ์ด๋ ๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋๋ฐ์ ํ ๋ ์ฐ์๋ค. ์ผ๋ฐ ํจ์์ new ํค์๋๋ฅผ ์ฌ์ฉํ์ฌ ํด๋์ค์ ์ธ์คํด์ค ๊ฐ์ฒด๋ฅผ ๋ง๋ค์๋ค.
function Phone(brand) {
this.brand = brand;
}
const phone = new Phone("Apple");
console.log(phone) // Phone {brand: "Apple"}
๊ฐ์ฒด ์์ ๊ฐ์ฒด ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ํ์ฉํ๊ธฐ๋ ํ๋ค.
ํ์ง๋ง, ์ฌ๊ธฐ์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค. ํจ์๊ฐ ํจ์ ํธ์ถ ์ฅ์์ ๋ฐ๋ผ์ ์๋์ด ๋ฌ๋ผ์ง๊ณ ์๋ฌ๊ฐ ๋ ์ ์๋ค. ์ด๋์ bind()๋ผ๋ ๋ฉ์๋๊ฐ ๋ฑ์ฅํ๋ค.
const obj = {
hi = "hello",
console: function() {
console.log(this.hi);
},
oneSecondLater: function() {
setTimeout(function() { console.log(this.hi)}, 1000)
}
}
obj.hi // "hello";
obj.onSecondLater // undefined;
const obj = {
hi = "hello",
console: function() {
console.log(this.hi);
},
oneSecondLater: function() {
setTimeout(function() { console.log(this.hi)}.bind(this), 1000)
}
`
obj.hi(); // "hello"
obj.onSecondLater() // "hello"
this ์ด๋ฐ ๊ณณ์ ์ฐ๋ฉด ๋ณต์กํด์ง๊ธฐ ๋๋ฌธ์, ํ์ฌ๋ class ๋ด์์ ์ธ์คํด์ค ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐ ํ ๋ ์ ์ฉํ๋ค. ๊ตณ์ด ๋ค๋ฅธ ๊ณณ์์ ์ฐ์ง ์์๋ ๋๋ค.
ํจ์๊ฐ ํธ์ถ ๋ ๋๋ง๋ค ๊ทธ ํจ์๋ "์ด๋ค ๊ฐ์ฒด"์ method์ผ ๊ฒ์ด๋ค. ํธ์ถ๋ ๋๋ง๋ค ๊ทธ "์ด๋ค ๊ฐ์ฒด"๋ฅผ ๋ฌผ์ด๋ณด๋ ๊ฒ์ด this
๊ฐ์ฒด๋ ์ฌ์ด๊ฑฐ ๊ฐ์ผ๋ฉด์๋ ํด๋ก์ ๋ this ์๋ฐ๊ฒ ๋์ค๋ฉด ํ์ธต ์๊ฐํด์ง๊ฒ ๋ง์์ง๋ค. ํนํ ๊ฐ์ฒด ๋ค๋ฃฐ ์ผ์ด ๋ง์ ๊ฑฐ๊ฐ์์ ๊ผผ๊ผผํ ์ฝ๋ ์ฐ์ต์ ํ์.