2017-02-14 91 views
1

我編程,可以在汗學院變換的多邊形圖書館的財產,但我不斷收到此錯誤:汗學院:無法讀取未定義

Cannot read property 'x' of undefined 

不帶行號。

我的代碼:

var Point = function(x,y) { 
    this.x = x; 
    this.y = y; 
}; 

Point.prototype.rotate = function(around,degrees) { 
    angleMode = "degrees"; 
    var aX = around.x; 
    var aY = around.y; 
    var cX = this.x; 
    var cY = this.y; 
    var dist = sqrt(sq(cX-aX)+sq(cY-aY)); 
    var currentTheta = asin(dist/cY); 
    var gamma = degrees+currentTheta; 
    this.x = cos(gamma)*dist+aX; 
    this.y = sin(gamma)*dist+aY; 
}; 

var Line = function(x1,y1,x2,y2) { 
    this.f = new Point(x1,y1); 
    this.s = new Point(x2,y2); 
}; 

Line.prototype.draw = function() { 
    line(this.f.x,this.f.y,this.s.x,this.s.y); 
}; 

Line.prototype.rotate = function(around,degrees) { 
    this.f = this.f.rotate(around,degrees); 
    this.s = this.s.rotate(around,degrees); 
}; 

var Polygon = function(x,y){ 
    if(x.length!==y.length){return;} 
    this.sides = x.length; 
    this.x = x; 
    this.y = y; 
    this.lines = new Array(this.sides); 
    this.lines[0] = new Line(this.x[this.sides-1],this.y[this.sides-1],this.x[0],this.y[0]); 
    for(var i=1;i<this.sides;i++){ 
     this.lines[i] = new Line(this.x[i-1],this.y[i-1]); 
    } 
}; 

Polygon.prototype.draw = function() { 
    for(var i=0;i<this.sides;i++){ 
     this.lines[i].draw(); 
    } 
}; 

Polygon.prototype.rotate = function(around,degrees) { 
    for(var i=0;i<this.sides;i++){ 
     this.lines[i].rotate(around,degrees); 
    } 
}; 

var p = new Polygon([10,20,40],[40,20,15]); 

var draw = function() { 
    background(255,255,255); 
    fill(0,0,0); 
    stroke(0,0,0); 
    p.rotate(new Point(20,20),1); 
    p.draw(); 
}; 

然而,我仍然不知道爲什麼它會拋出錯誤,特別是因爲它給錯誤所在沒有方向。

編輯


鏈接到項目: Transformation Library

+1

那個代碼本身並沒有給出這樣的錯誤,還有別的嗎? –

+0

@JaromandaX這些功能在khanacademy中是默認的,填充和描邊用於繪製。 –

+0

編輯:添加到項目鏈接@JaromandaX –

回答

3

讓我們先從你的Point類及其rotate()功能:

Point.prototype.rotate = function(around,degrees) { 
    angleMode = "degrees"; 
    var aX = around.x; 
    var aY = around.y; 
    var cX = this.x; 
    var cY = this.y; 
    var dist = sqrt(sq(cX-aX)+sq(cY-aY)); 
    var currentTheta = asin(dist/cY); 
    var gamma = degrees+currentTheta; 
    this.x = cos(gamma)*dist+aX; 
    this.y = sin(gamma)*dist+aY; 
}; 

這個函數做一些數學並設置this.xthis.y變量。到目前爲止這麼好(免責聲明:我沒有檢查過這個數學,但那不是重點)。但是請注意,這個函數不會返回任何東西。

現在讓我們去你的Line類及其rotate()功能:

Line.prototype.rotate = function(around,degrees) { 
    this.f = this.f.rotate(around,degrees); 
    this.s = this.s.rotate(around,degrees); 
}; 

這臺fs變量從rotate()函數的返回值。但是請等待,Point類中的rotate()函數不會返回任何內容!所以現在this.fthis.s都是undefined

你有類似的問題,你的Polygon類調​​用Line類的rotate()函數。

因此要解決您的問題,您需要使用rotate()函數來返回某些內容,或者只需調用它們而不是期望返回值。

退一步,我想知道你爲什麼要自己做這一切。處理有它自己的rotate()功能,爲你做這一切。你爲什麼不直接用它們呢?

+0

謝謝!我錯過了... 我自己寫這個,因爲它是一個項目。 –

+1

@EricHe如果這解決了您的問題,您可能希望將其標記爲答案 –