我的程序中有以下对象
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
呢?
也感谢对我的代码的任何其他评论和帮助。