3

我的程序中有以下对象

function Player(id) {
    this.id = id;
    this.healthid = this.id + "health";
    this.displayText = "blah blah";
    this.inFight = false;
    this.currentLocation = 0;
    this.xp = 0;
    this.level = 1;
}

var player = new Player('player');

player.currentHealth = player.health;

我像这样打印出属性名称

function displayStats() {
    var statsHtml = "";
    for ( var prop in player ) {
        statsHtml += "<p id = 'displayPlayerHealth'>" + prop + "</p>";
    }

    $('.stats').html( statsHtml);
    console.log(statsHtml);
}

displayStats();

效果很好,但是我这样声明的其他属性

Object.defineProperty(player,"health",{ 
    set: function() { 
    return 10 + ( this.level * 15 );
    }, 
    get: function() { 
    return 10 + ( this.level * 15 );
    } 
} );


Object.defineProperty(player,"strength",{ 
    set: function() { 
        return ( this.level * 5 );
    }, 
    get: function() { 
        return ( this.level * 5 );
    } 
} );

Object.defineProperty(player,"hitRating",{ 
    set: function() { 
        return 3 + ( this.level );
    }, 
    get: function() { 
        return 3 + ( this.level );
    } 
} );

不要在这里打印小提琴

现在我输入这段代码以确保它们被定义

console.log(player.hitRating);

这给了我4,正是我所期望的。

那么我如何遍历创建的对象的属性Object.defineProperty呢?

也感谢对​​我的代码的任何其他评论和帮助。

4

1 回答 1

8

让他们enumerable: true

Object.defineProperty(player,"hitRating",{ 
    set: function() { 
        return 3 + ( this.level );
    }, 
    get: function() { 
        return 3 + ( this.level );
    },
    enumerable: true 
} );

小提琴

来自MDN

enumerable
当且仅当在枚举相应对象的属性期间显示此属性时为真。默认为 false

于 2013-09-01T23:06:02.980 回答