2014-11-20 6 views
1

개체 메서드를 실행하는 데 약간의 문제가 있으며 OOP에 처음 익숙합니다. 나는 다음과 같은 생성자 클래스가 있습니다프로토 타입 메서드는 "undefined"를 반환합니다.

그때마다 "덩어리"에 다음과 같은 방법을 프로토 타입 할
function Blob(c, maxRadius, points, v) { 

    this.vector = v; 
    this.maxVector = 5; 
    this.center = c; 


    this.path = new Path(); 
    this.path.closed = true; 
    for (var i = 0; i < points; i++) { 
     var delta = new Point({ 
      length: (maxRadius * 0.5) + (Math.random() * maxRadius * 0.5), 
      angle: (360/points) * i 
     }); 
     this.path.add(center + delta); 
    } 
    this.path.smooth(); 
    this.path.fillColor = colors[i % 3]; 
}; 

객체를

Blob.prototype = { 
    iterate: function() { 
     this.checkBorders(); 
     if (this.vector.length > this.maxVector) 
      this.vector.length = this.maxVector 
     this.center += this.vector; 

    }, 
    checkBorders: function() { 
     var size = view.size; 
     if (this.center.x < -this.radius) 
      this.center.x = size.width + this.radius; 
     if (this.center.x > size.width + this.radius) 
      this.center.x = -this.radius; 
     if (this.center.y < -this.radius) 
      this.center.y = size.height + this.radius; 
     if (this.center.y > size.height + this.radius) 
      this.center.y = -this.radius; 
    } 
}; 

그때 다시 전달하는 새로운 함수 내 생성자 클래스를 호출 생성자 클래스에 필요한 인수 :

function createPaths() { 
    var radiusDelta = values.maxRadius - values.minRadius; 
    var pointsDelta = values.maxPoints - values.minPoints; 

    for (var i = 0; i < values.paths; i++) { 
     var radius = values.minRadius + Math.random() * radiusDelta; 
     var points = values.minPoints + Math.floor(Math.random() * pointsDelta); 
     var center = view.size * Point.random(); 
     var vector = new Point({ 
      angle: 360 * Math.random(), 
      length: Math.random() * 10 
     }); 

     blobs.push(Blob(center, radius, points, vector)); 
    }; 
} 

그러나 나는 시도하고 함수 내에서 액세스를 할 때 :

function onFrame() { 
    for (var i = 0; i < blobs.length - 1; i++) { 
     blobs[i].iterate(); 
    } 
} 

"catch되지 않은 형식 오류 : 정의되지 않은 재산 '으로 반복'을 읽을 수 없습니다"를 반환,이 프로토 타입이 실패하는 것을 다음 날 것으로 보인다? onFrame() 내에서 "blobs [i]"콘솔을 만들면 찾을 수있는 객체 배열을 반환하므로 클래스 생성자 함수에 문제가없는 것처럼 보입니다.

+0

프로토 타입이 아닙니다. 당신의'blobs' 배열은 어딘가에'undefined' 값을 가지고 있습니다. – Brennan

+1

나는 그것을 다시 정의하는 대신 프로토 타입에 추가 할 것이다 :'Blob.prototype.iterate = function() {...}' – sebnukem

+0

'blobs' 배열을 어떻게 채우겠습니까? –

답변

2

변경하면 다른 오브젝트

blobs.push(new Blob(center, radius, points, vector)); 

당신은 현재 코드 만 아무 것도 반환하지 않는 Blob 기능을 실행을 만들 수 있도록 새로운 사용하는 충전 배열 (undefined)

+0

얼굴에 자신을 때리는 느낌이 드십니까?! 하하는 그 점에 대해 감사 드리며 분명히 신선한 눈 쌍이 필요했습니다. – user3586963

0

대신의 프로토 타입에 추가 그것을 재정의하는 것 :

Blob.prototype.checkBorders = function() { ... }; 
Blob.prototype.iterate = function() { ... }; 

그리고 잊지 마라. new 키워드는 새 Blob 객체를 인스턴스화합니다.