반응형

프로토타입을 사용하는 예

function Person(name, blog) {
    this.name = name;
    this.blog = blog;
}

Person.prototype.getName = function() {
    return this.name;
};
Person.prototype.getBlog = function() {
    return this.blog;
};

var shiro = new Person("shiro", "shiro21.tistory.com");
var stranger = new Person("stranger", "google.com");

console.log(shiro.getName()); // shiro
console.log(shiro.getBlog()); // shiro21.tistory.com
console.log(stranger.getName()); // stranger
console.log(stranger.getBlog()); // google.com

Person.prototype 코드부분은 constructor.prototype코드로 접근할 수 있다.

Person이라는 생성자의 prototype속성을 설정하고 있는 것이다.

이후 새로 생성된 shiro와 stranger객체는 내부적으로 이 prototype객체를 참고하여 prototype객체가 가지고 있는 getName()과 getBlog()함수를 사용할 수 있다.

이는 '생성자를 통해서 생성한 객체들이 prototype을 공유한다'라고 생각하면 된다.

 

객체 생성 후 prototype의 수정 예

function Person(name, blog) {
    this.name = name;
    this.blog = blog;
}

Person.prototype.getName = function() {
    return this.name;
};
Person.prototype.getBlog = function() {
    return this.blog;
};

var shiro = new Person("shiro", "shiro21.tistory.com");
var stranger = new Person("stranger", "google.com");


Person.prototype.introduce = function() {
    console.log("Hi!, my name is " + this.name + ", plase visit my blog " + this.blog);
};

shiro.introduce(); // Hi!, my name is shiro, plase visit my blog shiro21.tistory.com

이렇게 이미 생성자를 통해 생성된 객체라도 나중에 생성자의 프로토타입에 새로운 속성을 추가할 수 있고, 이렇게 추가된 속성 또한 모든 객체가 공유한다. 

 

이미 정의된 prototype의 속성 수정 예

Person.prototype.introduce = function() {
    console.log("Hello, " + this.name + " ! ! !");
};
shiro.introduce(); // Hello, shiro ! ! !

기존에 선언해 두었던 속성을 다시 수정할 수 있다.

 

prototype에 변수 추가 예

Person.prototype.gender = "male";

console.log(shiro.gender); // male
console.log(stranger.gender); // male

프로토타입에 함수가 아닌 변수도 추가하여 공유가 가능하다.

 

prototype에 정의된 변수를 수정하는 예

stranger.gender = "female";
console.log(stranger.gender); // female
console.log(shiro.gender); // male
console.log(Person.prototype.gender) // male

위 코드를 실행하면 stranger객체의 gender값은 female로 바뀌었지만, shiro객체의 gender값은 여전히 male을 출력한다. 그런데 특이한 점은 stranger.gender였던 Person.prototype.gender값이 female로 바뀌지 않고 여전히 male로 유지되고 있다는 점이다.

 

반응형

+ Recent posts