声明具有无效功能的javascript对象属性

Mat*_*ler 3 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
}
Run Code Online (Sandbox Code Playgroud)

我的理解是你可以给一个对象一个函数作为属性.

但是,当alert(player.health)我得到:

function() { return 10 + (this.level * 15) }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?您是否无法以这种方式声明对象属性?有没有办法自动生成player.health以后调用的任何时间的值?

Jan*_*roň 12

如果你想在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
Run Code Online (Sandbox Code Playgroud)


Bar*_*mar 9

player.health是一个功能.要调用一个函数,你必须()在它之后:

alert(player.health());
Run Code Online (Sandbox Code Playgroud)