본문 바로가기

JavaScript/JavaScript기초

[Javascript] 함수의 prototype

함수의 prototype 프로퍼티

함수를 new 연산자를 통해 생성하면 객체가 생성됨

 

함수를 객체로 생성 전 함수.prototype = obj 로 생성될 객체의 [[prototype]]를 설정할 수 있음

function myFunc(a,b){
	
    this.a = a;
    this.b = b;
}

let obj = {
	
    c:3,
    d:4
}	

//Function.prototype를 이용하여 obj를 참조시킴
myFunc.prototype = obj

//new 연산자를 이용하여 함수를 객체로 생성
let myFuncObj = new myFunc(1,2);

for(let key in myFuncObj)
	console.log(`${key} : ${myFuncObj[key]}`);

 

myFunc에 obj가 참조된 것을 볼 수 있음

 

함수의 constructor 프로퍼티

함수의 prototype 프로퍼티는 기본적으로 constructor 프로퍼티를 가지고 있는데, 이 프로퍼티의 값은 함수 자기 자신을 나타냄

function myFunc(){}

console.log(myFunc.prototype.constructor);

 

 

즉 함수로 만든 객체도 [[prototype]] 를 거쳐서 constructor 프로퍼티를 사용할 수 있음

function myFunc(){}

let myObj = new myFunc();

//함수 myFunc를 가리킴
console.log(myObj.constructor);

 

 

참조: https://ko.javascript.info/function-prototype