2013-08-30 36 views
2

我正在做一個蹩腳的基於文本的遊戲,我做了一個對象的球員,像這樣:聲明JavaScript對象屬性與功能不工作

var player = { 
    displayText: "<span>you</span>", 
    currentPosition: 0, 
    level: 1, 
    health: function() { return 10 + (this.level * 15) }, 
    strength: function() { return this.level * 5 }, 
    hitRating: 4 
} 

我的理解是,你可以給一個對象的函數作爲財產。

然而,當我alert(player.health)我得到:

function() { return 10 + (this.level * 15) } 

我在做什麼錯?你不能這樣聲明一個對象屬性嗎?有沒有辦法自動生成值player.health任何時候它被稱爲稍後?

回答

8

player.health是一個函數。要調用一個函數,你必須把()後:

alert(player.health()); 
3

您需要調用的函數,player.health()

9

如果你想用JS對象訪問創建屬性,這樣做正確的方法是使用Object.defineProperty

你的情況:

// original object 
var player = { 
    displayText: "<span>you</span>", 
    currentPosition: 0, 
    level: 1, 
    // health: function() { return 10 + (this.level * 15) }, 
    strength: function() { return this.level * 5 }, 
    hitRating: 4 
} 

// create property with accessor method 
Object.defineProperty(player, "health", { 
    get: function() { 
     return 10 + (player.level * 15) 
    } 
}) 

// call the property 
alert(player.health); // 25 
player.level++; 
alert(player.health); // 40