컴퓨터이야기/WEB

javascript에서 class 만드는 방법.

백구씨쥔장 2008. 6. 20. 11:52
var Position = function(x, y) {
    this.xpos = x;
    this.ypos = y;
}

Position.prototype.distance = function() {
    var x2 = this.xpos * this.xpos;
    var y2 = this.ypos * this.ypos;
    return Math.sqrt(x2 + y2);
};
var Position = function(x,y) {
    this.xpos = x;
    this.ypox = y;
    this.distance = function() {
        var x2 = this.xpos * this.xpos;
        var y2 = this.ypos * this.ypos;
        return Math.sqrt(x2 + y2);
    };
};

이렇게 클래스를 만들었는데 여기는 한가지 문제가 있다.
Position 오브젝트를 만들 때마다 바로 멤버 메소드 (여기서는 distance())의 포인터가 매회 만들어진다.
불필요한 메모리가 만들어지는 것이다.

첫 번째처럼 만들어야 불필요한 메모리를 만들지 않는다.

출처: http://faidcy.tistory.com/68