2015-12-15 31 views
-1

我正在學習一個教程,並在其中聲明瞭變量,然後繼續對他們做一些我不明白的事情。關於變量的簡單的Javascript事情

var player, ai, ball; 

player = { // this is the code I am referring to 
    x: null, 
    y: null, 
    width: 20, 
    height: 100, 

    update: function(){}, 
    draw: function(){ 
     ctx.fillRect(this.x, this.y, this.width, this.height); 
    } 
}; 

他在變量內添加變量嗎? 謝謝。

+0

它是一個對象。 – epascarello

+0

閱讀關於JavaScript數據結構的基本教程。 – 2015-12-15 04:08:53

回答

1

是的,它聲明瞭一個javascript對象。

你也許可以使用一些reading

的對象變量太多。但對象可以包含很多值。

+0

感謝您的幫助,我現在明白了。 – RyanD

0

此代碼爲變量分配一個對象。每個冒號左側的字符串是一個屬性名稱。該代碼將值分配給屬性,其中最後兩個分配要調用的函數。

的屬性可以被稱爲像這樣:

var playerAge = player.age; 

職能將同樣被稱爲:

player.draw(); 
+0

感謝您的幫助,我現在明白了。 – RyanD

0

不完全只是一個變量中設置變量。他將player設置爲等於一個Javascript對象。此對象包含如xy以及功能updatedraw的成員。

JS Object documentation

+0

感謝您的幫助,一個快速的成員(或元素)是他們定義的Javascript或我可以去叫它MyX,MyY? – RyanD

+0

從技術上講,這些不稱爲成員。常用的方法是調用它們的屬性。 – 2015-12-15 04:09:37

-1
var player, ai, ball; // this declare variables 

player = { // player = {} , it means player is a object 
    x: null, // this object have a var call x; 
    y: null, 
    width: 20, 
    height: 100, 

    // this object has a property "update", and update is a function; 
    update: function(){}, 

    // this object has a property "draw", and draw is a function; 
    draw: function(){ 
     ctx.fillRect(this.x, this.y, this.width, this.height); 
    } 
}; 
+0

非常感謝您的幫助,我現在明白了。 – RyanD

+1

我不知道'this object has var update'是什麼意思。 'update'在這裏不是一個變量,它是一個屬性,這是一個非常不同的東西。 – 2015-12-15 04:10:16

+0

你是對的!更新是一個屬性 – LYan