-
PrototypeWeb/Node.js 2024. 6. 7. 21:48
자바 스크립트에서 객체 지향을 하기 위해 사용하는 개념
- prototype은 생성자 함수가 실행될 때 반환해주는 프로퍼티
- __proto__ 는 상위 prototype을 접근할 때 사용
사용 예시
function Ultra(this.test = "testing"){} Ultra.prototype.hello = "world" function Super(){} Super.prototype = new Ultra() function Sub(){} Sub.prototype = new Super() var o = new Sub()
순서
- 변수 o에 넣기 위한 생성자 함수 new Sub() 실행
- Sub의 prototype 즉, 변수 o 에게 반환해주기 위한 객체를 생성하기 위해 prototype사용
- Sub.prototype이 생성자 함수 new Super()
- Sub.prototype에 넣기 위한 생성자 함수 new Super() 실행
- Ultra까지 반복
- Ultra.prototype에 hello : “world”를 넣음 ⇒ key : value 설정
따라서 console.log(o.hello) // world 이다
Prototype 예제
console.log(o.hello) // world console.log(o.__proto__ == Sub.prototype) // true console.log(o.__proto__ == Super.prototype) // false // o의 객체를 반환해 주는 것은 Sub.prototype이기 때문 console.log(o.__proto__.__proto__ == Super.prototype) // true console.log(o.test) // testing //---------------------------------------- console.log(o.constructor) // [Function : Ultra()] // o의 생성자 함수는 prototype을 따라 올라가서 결국 Ultra 함수 이기 때문 console.log(Sub.constructor) // [Function : Function] console.log(Super.constructor) // [Function : Function] // function Sub와 function Super의 생성자는 Function 이기 때문 console.log(Sub.__proto__ == Super.prototype) // false console.log(Sub.prototype.__proto__ == Super.prototype) // true console.log(Sub.__proto__ == Function.prototype) // true // 즉, function Sub의 __proto__ 는 Function 이고 // Sub의 prototype의 __proto__는 Super의 prototype이다 //------------------------------------------ console.log(Sub.constructor) // [Function : Function] Sub.constructor = "hacked" console.log(Sub.constructor) // hacked // constructor가 생성자를 가리키지만 Sub.constructor에 대입하더라도 생성자 변경X // function Sub에 key : value 인 "constructor" : "hacked"가 생성 //------------------------------------------ console.log(Function.__proto__ == Object.prototype) // false console.log({}.__proto__ == Object.prototype) // true console.log(Function.__proto__ == Function.prototype) // true console.log(Function.__proto__.__proto__ == Function.prototype) // false console.log(Function.__proto__.__proto__ == Object.prototype) // true //Function prototype 은 {} 빈 객체, 하지만 이것은 Object의 prototype은 아님 //하지만 빈 객체의 __proto__는 Object의 prototype이므로 다음과 같다 console.log(Ultra.prototype.hello.__proto__ == Ultra.prototype) // false console.log(Ultra.prototype.hello) // world console.log(Ultra.prototype.hello.__proto__ == String.prototype) // true // Ultra의 prototype내에 존재하는 hello의 값은 문자열 이다 // 따라서 String의 prototype이다
'Web > Node.js' 카테고리의 다른 글
Express (1) 2024.06.07 Node.js 기초 (1) 2024.06.07