React, Javascript
[ Javascript Prototype ] 2. Prototype property & instance member
짹데브
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"
반응형