-
[ Javascript Prototype ] 2. Prototype property & instance memberReact, Javascript 2021. 6. 20. 17:23반응형
아래
Circle
class에는 instance member로draw
메소드가 있다.function Circle(radius) { this.radius = radius; this.draw = function() { console.log('draw') } }
Circle
class로 만든 객체c1
,c2
는draw
function을 instance method로 가지게 된다.const c1 = new Circle(1); const c2 = new Circle(2);
draw
method를c1
,c2
의 prototype인Circle
에 추가하려며 어떻게 해야 될까?c1.__proto__ == Circle.prototype // true
c1
의 prototype은Circle.prototype
으로 접근할 수 있고, 이 object에 key, value를 추가하는 형식으로draw
method를 prototype에 추가할 수 있다.function Circle(radius) { this.radius = radius; } Circle.prototype.draw = function() { console.log('draw'); } const c3 = new Circle(1);
Prototype의 property로 만드는 것과 instance method로 만드는 것의 차이점은 뭘까?
instance method는 각 instance마다 만들어지는 method이다. 이미 instanciation을 한 뒤에는 모든 객체에 대해서 별도로 수정을 해주어야 한다.
function Circle(radius) { this.radius = radius; this.draw = function() { console.log('draw') } } const c1 = new Circle(1); const c2 = new Circle(2); c1.draw = () => { console.log("update draw")}; c1.draw(); // "update draw" c2.draw(); // "draw"
하지만 prototype property라면, 모든 객체애 대해서 prototype을 수정하는 것으로 동일하게 적용을 시킬 수 있다.
function Circle(radius) { this.radius = radius; } Circle.prototype.draw = () => { console.log("draw")} const c1 = new Circle(1); const c2 = new Circle(1); Circle.prototype.draw = () => { console.log("update draw")} c1.draw(); // "update draw" c2.draw(); // "update draw"
반응형'React, Javascript' 카테고리의 다른 글
[React Native] 원하는 시뮬레이터에서 실행시키기 (0) 2023.11.10 [NestJS] #2. First steps (0) 2021.07.21 [NestJS] #1. 소개 & 철학 (0) 2021.07.21 [javascript prototype] Prototype을 이용한 상속 (0) 2021.06.20 [ Javascript Prototype ] 1. Prototype Chain (0) 2021.06.11