DEV Community

Randy Rivera
Randy Rivera

Posted on

Understanding Own Properties

  • Continued.
  • In the following example, the Dog constructor defines two properties: name and numLegs:
function Dog(name) {
  this.name  = name;
  this.numLegs = 4;
}

let greyHound = new Dog("Sakura");
let bullDog = new Dog("Tanjiro");
Enter fullscreen mode Exit fullscreen mode
  • name and numLegs are called own properties, because they are defined directly on the instance object. That means that greyHound and bullDog each has its own separate copy of these properties. In fact every instance of Dog will have its own copy of these properties. The following code adds all of the own properties of greyHound to the array ownProps:
function Dog(name) {
  this.name  = name;
  this.numLegs = 4;
}

let greyHound = new Dog("Sakura");
let ownProps = [];

for (let properties in greyHound) {
  if (greyHound.hasOwnProperty(properties)) {
    ownProps.push(properties);
  }
}

console.log(ownProps); // the console would display the value ['name', 'numLegs']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)