ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

53. ๋ฌด์—‡์ด ์ถœ๋ ฅ ๋ ๊นŒ์š”?

function Car() {
  this.make = "Lamborghini";
  return { make: "Maserati" };
}

const myCar = new Car();
console.log(myCar.make);
  • A: "Lamborghini"
  • B: "Maserati"
  • C: ReferenceError
  • D: TypeError

 

 


 

new User(...)๋ฅผ ์จ์„œ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.

  1. ๋นˆ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด this์— ํ• ๋‹นํ•ฉ๋‹ˆ๋‹ค.
  2. ํ•จ์ˆ˜ ๋ณธ๋ฌธ์„ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค. this์— ์ƒˆ๋กœ์šด ํ”„๋กœํผํ‹ฐ๋ฅผ ์ถ”๊ฐ€ํ•ด this๋ฅผ ์ˆ˜์ •ํ•ฉ๋‹ˆ๋‹ค.
  3. this๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
function User(name) {
  // this = {};  (๋นˆ ๊ฐ์ฒด๊ฐ€ ์•”์‹œ์ ์œผ๋กœ ๋งŒ๋“ค์–ด์ง)

  // ์ƒˆ๋กœ์šด ํ”„๋กœํผํ‹ฐ๋ฅผ this์— ์ถ”๊ฐ€ํ•จ
  this.name = name;
  this.isAdmin = false;

  // return this;  (this๊ฐ€ ์•”์‹œ์ ์œผ๋กœ ๋ฐ˜ํ™˜๋จ)
}

 

์ƒ์„ฑ์ž์™€ return๋ฌธ

์ƒ์„ฑ์ž ํ•จ์ˆ˜์—” ๋ณดํ†ต return ๋ฌธ์ด ์—†์Šต๋‹ˆ๋‹ค. ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•  ๊ฒƒ๋“ค์€ ๋ชจ๋‘ this์— ์ €์žฅ๋˜๊ณ , this๋Š” ์ž๋™์œผ๋กœ ๋ฐ˜ํ™˜๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ˜ํ™˜๋ฌธ์„ ๋ช…์‹œ์ ์œผ๋กœ ์จ ์ค„ ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.

๊ทธ๋Ÿฐ๋ฐ ๋งŒ์•ฝ return ๋ฌธ์ด ์žˆ๋‹ค๋ฉด ์–ด๋–ค ์ผ์ด ๋ฒŒ์–ด์งˆ๊นŒ์š”? ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฐ„๋‹จํ•œ ๊ทœ์น™์ด ์ ์šฉ๋ฉ๋‹ˆ๋‹ค.

  • ๊ฐ์ฒด๋ฅผ return ํ•œ๋‹ค๋ฉด, this ๋Œ€์‹  ๊ฐ์ฒด๊ฐ€ ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค.
  • ์›์‹œํ˜•์„ return ํ•œ๋‹ค๋ฉด, return๋ฌธ์ด ๋ฌด์‹œ๋ฉ๋‹ˆ๋‹ค.
  • return ๋’ค์— ๊ฐ์ฒด๊ฐ€ ์˜ค๋ฉด ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋Š” ํ•ด๋‹น ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๊ณ , ์ด ์™ธ์˜ ๊ฒฝ์šฐ๋Š” this๊ฐ€ ๋ฐ˜ํ™˜๋˜์ฃ .

 

 

 

return ๊ฐ’์ด ์กด์žฌํ•œ๋‹ค๋ฉด ๊ฑ”๊ฐ€ ๋ณ€์ˆ˜์— ํ• ๋‹น๋จ
๋”ฐ๋ผ์„œ myCar ์—๋Š” { make: "Maserati" } ์ด๋ผ๋Š” ๊ฐ์ฒด๊ฐ€ ํ• ๋‹น๋œ๋‹ค.

์ƒ์„ฑ์žํ•จ์ˆ˜์—์„  return์„ ๋ช…์‹œํ•˜์ง€ ์•Š๋Š” ํŽธ์ด ์ข‹๊ฒ ...๋‹ค?

 

 

๋ฌธ์ œ์˜ ์ถœ์ฒ˜ : https://github.com/lydiahallie/javascript-questions/blob/master/ko-KR/README-ko_KR.md#53-%EB%AC%B4%EC%97%87%EC%9D%B4-%EC%B6%9C%EB%A0%A5-%EB%90%A0%EA%B9%8C%EC%9A%94

ํ•ด๋‹ต์˜ ์ถœ์ฒ˜ : https://ko.javascript.info/constructor-new#ref-901

๋Œ“๊ธ€