Как перебрать свойства объекта, созданные Object.defineProperty
У меня есть следующий объект в моей программе
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
?
любые другие комментарии и помощь по моему коду также приветствуются.
1 ответ
Решение
Просто сделай их enumerable: true
Object.defineProperty(player,"hitRating",{
set: function() {
return 3 + ( this.level );
},
get: function() {
return 3 + ( this.level );
},
enumerable: true
} );
От MDN
перечислимый
Значение true, если и только если это свойство отображается при перечислении свойств соответствующего объекта. По умолчанию false.