4

In the following code, I am having trouble figuring out how to log (in the console) the name and numLegs properties of Penguin (i.e., "emperor" and 2), without changing the inside of the function?

function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
}

var emperor = new Penguin("emperor");

How can I do that?

talemyn
  • 7,422
  • 4
  • 27
  • 47
Harman Nieves
  • 121
  • 2
  • 8

2 Answers2

3

Simply accessing it's properties. Your emperor is an object, which means that you can access properties with . syntax.

function Penguin(name){

   this.name=name;

   this.numLegs=2;

}

var emperor = new Penguin("emperor");

console.log(emperor.name);
console.log(emperor.numLegs);
Suren Srapyan
  • 62,337
  • 13
  • 111
  • 105
0

You can use a simple function :

for (var key in emperor) {
  if (emperor.hasOwnProperty(key)) {
    console.log(key + " -> " + emperor[key]);
  }
}

or write

console.log(emperor.numLegs);
console.log(emperor.name);

Reference: How do I loop through or enumerate a JavaScript object?

Community
  • 1
  • 1
Ankush
  • 417
  • 1
  • 6
  • 14