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,822
  • 4
  • 31
  • 52
Harman Nieves
  • 151
  • 1
  • 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
  • 66,568
  • 14
  • 114
  • 112
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
  • 499
  • 1
  • 7
  • 17