我的程序中有以下对象
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 );
}
} );
请勿打印fiddle here。
现在我输入此代码以确保它们已定义
console.log(player.hitRating);
给了我4
,正是我所期待的。
那么如何循环使用Object.defineProperty
创建的对象的属性?
对我的代码的任何其他评论和帮助也表示赞赏。