2013-10-07 16 views
0

我有一個HTML文件,看起來像這樣:傳遞上下文函數[圖形的Javascript]

<!DOCTYPE html> 
<html> 
    <head> 
     <link rel = "stylesheet" 
       type = "text/css" 
       href = "landscape.css" /> 
    </head> 
    <body> 
     <h1 id = "heading">My Landscape</h1> 
     <canvas id = "landscape" width = "800" height = "600"> 
      landscape 
     </canvas> 
     <script type = "text/javascript" 
       src = "landscape.js"> 
     </script> 
    </body> 
</html> 

和這裏的landscape.js:

var canvas = document.getElementById('landscape'); 
var context = canvas.getContext('2d'); 
context.fillStyle = "#ff0000"; 
context.fillRect(20, 20, 150, 100); 
var mySky = new sky(40, 40); 
mySky.render(context); 

function sky(x, y){ 

    this.x = x; 
    this.y = y; 

    function render(theContext){ 

     theContext.fillStyle = "#00ff00"; 
     theContext.fillRect(x, y, 150, 100); 

    } 

} 

現在,第一部分 - 「 context.fillStyle =「和」context.fillRect()「 - 工作正常。它在我的瀏覽器中顯示爲紅色矩形(在Mac上使用Firefox)。

但是,當我嘗試創建一個天空物體,然後通過上下文來渲染它時,沒有任何反應。我無法弄清楚爲什麼它不會在天空物體上執行渲染功能。

我誤解了JS對象的工作方式嗎?

這是(非常簡單的)CSS,以防有人想嘗試運行它。

/* landscape.css */ 

#landscape{ 
    border: 2px solid black; 
} 

回答

4

那是因爲你的渲染功能是private,因爲它是從你的sky()函數內部才能訪問。

爲了它的工作,你需要(以this通過添加屬性)提供外部可訪問

嘗試

this.render = function(thecontext) { 

} 
+0

謝謝你,成功了!我很好奇我是否誤解了w3schools上的教程(是的,我知道,w3fools以及所有這些),還是他們做錯了什麼:http://www.w3schools.com/js/tryit。 asp?filename = tryjs_create_object3有什麼見解? –

+1

從你已經鏈接的例子:你錯過了這一行:'this.changeName = changeName;'它將「private」函數changeName賦值給公共可訪問的屬性。 – Alan

+0

啊,我明白了。謝謝,現在有道理。 –