๐Ÿ“• Language/JavaScript

[Javascript] instanceof, arguments

a n u e 2022. 4. 29. 11:41
 function a() 
 {
	if(!(this instanceof arguments.callee))
	{
		return new a();
	}
 }

 1. function 

  function๋„ ํ•˜๋‚˜์˜ ๊ฐ์ฒด์ด๋‹ค.



 2. this, new

  this๋Š” ํ•จ์ˆ˜์˜ ํ˜ธ์ถœ์ž๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.
  ์ฆ‰์‹œ์‹คํ–‰ํ•จ์ˆ˜์ฒ˜๋Ÿผ ์•ž์— ํ˜ธ์ถœ์ž๊ฐ€ ์—†๋‹ค๋ฉด, ๊ธฐ๋ณธ์ ์œผ๋กœ window ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.
  ํ•จ์ˆ˜ ์„ ์–ธ ์‹œ, ์•ž์— new๊ฐ€ ๋ถ™๊ณ  ์•ˆ๋ถ™๊ณ ๋Š” ์™„์ „ ๋‹ค๋ฅธ ๊ฒฐ๊ณผ๋ฅผ ๋ถ€๋ฅธ๋‹ค.
  

  a(); //a ํ•จ์ˆ˜ ์† this๋Š” window ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.
  var func = a(); //a ํ•จ์ˆ˜ ์† this๋Š” window ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค. (์ฐธ๊ณ  func; ๋ฅผ ํ•˜๋ฉด, a()๊ฐ€ ์‹คํ–‰๋œ๋‹ค.)
  new a(); //a ํ•จ์ˆ˜ ์† this๋Š” ์ƒˆ๋กœ ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค. 
  var func = new a(); //a ํ•จ์ˆ˜ ์† this๋Š” ์ƒˆ๋กœ ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.  (์ฐธ๊ณ  func; ๋ฅผ ํ•˜๋ฉด, ์ƒˆ๋กœ ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.)
  
  //this๋ฅผ ๋ณ€๊ฒฝํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด? call / apply ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉ

 3. A instacneof B

  ์•ž ๋’ค๋กœ, ์ธ์ž๋ฅผ ๋ฐ›์•„์„œ ๋น„๊ตํ•˜์—ฌ boolean๊ฐ’ ๋ฐ˜ํ™˜

  Q. A๊ฐ€ B์˜ ์ž์‹์ธ๊ฐ€?
  Q. A๋Š” B์˜ prototype chain ํ•˜์œ„์ธ๊ฐ€?

 

var Person = function()
{
 this.name = "kimeuna"
 this.age = "29"
};
var Kimeuna = new Person();

Kimeuna instacneof Person; //true
Kimeuns instacneof Object; //true
[1, 2] instanceof Array ; //true
{ a: "aa" } instanceof Object ; //true

true instanceof Boolean ; //false
"A" instanceof String ; //false

var str = new String("def");
var str2 = "abc";
str instanceof String; //true
str2 instanceof String; //false



 4. arguments

   arguments๋Š” function ๊ฐ์ฒด์˜ ๊ณ ์œ  ํ”„๋กœํผํ‹ฐ
   

function myfunc(a,b,c)
{
 console.log(arguments[0]);
 return arguments;
}
myfunc(1,2,3) //1

/**
Arguments
0 : 1
1 : 2
2 : 3

 * callee? ํ•จ์ˆ˜ ์ž๊ธฐ ์ž์‹ ์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•ญ๋ชฉ

*/

5. ํ•ด์„

  if(!(this instanceof arguments.callee))

   - a๋ผ๋Š” function์˜ ํ˜ธ์ถœ์ž(this)๊ฐ€ ์ด ํ•จ์ˆ˜(arguments.callee)์— ์ž์‹์ธ์ง€, prototype chain์— ์†ํ•ด์žˆ์ง€ ์•Š์€์ง€ ํŒ๋ณ„
  

return new a();

   - ์†ํ•ด์žˆ์ง€ ์•Š๋‹ค๋ฉด, new a()๋ฅผ returnํ•ด์ค€๋‹ค.

 

 


โ€‹

์ถœ์ฒ˜

https://gogoonbuntu.tistory.com/46