【问题标题】:declaring javascript object property with a function not working使用不起作用的函数声明 javascript 对象属性
【发布时间】:2013-09-02 14:27:45
【问题描述】:

我正在制作一个蹩脚的基于文本的游戏,我制作了一个像这样的对象播放器:

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 的任何时候自动生成它的值?

【问题讨论】:

    标签: javascript object defineproperty


    【解决方案1】:

    如果你想在 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
    

    【讨论】:

      【解决方案2】:

      player.health 是一个函数。要调用一个函数,你必须在它后面加上()

      alert(player.health());
      

      【讨论】:

        【解决方案3】:

        你需要调用函数player.health()

        【讨论】:

          猜你喜欢
          • 2018-06-30
          • 1970-01-01
          • 2016-01-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-03
          相关资源
          最近更新 更多