Question

i have the following object in my program

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;

and i print out the property names like so

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

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

displayStats();

which works fine, however the other property's which i declare like so

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 );
    } 
} );

dont print out fiddle here.

now i put in this code to make sure they are defined

console.log(player.hitRating);

which gives me 4, exactly what i expect.

so how do i loop through the property's of a object which were created with Object.defineProperty?

any other comments and help on my code are also appreciated.

Était-ce utile?

La solution

Just make them enumerable: true

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

fiddle

From MDN

enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top