3

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

and how do you make members (functions, this variables, etc), not defined by Object.defineProperty NOT enumerable? Any way to do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.