about 1 year ago

I defined two properties (one enumerable and one not enumerable) on a prototype object and two properties on an instance object. I want to see what is the difference among for...in, Object.keys() and Object.getOwnPropertyNames():

function Person(){}

Object.defineProperty(Person.prototype, 'grade', {
  configurable: true,
  enumerable: true,
  writable: true,
  value: '5'
});

Object.defineProperty(Person.prototype, 'school', {
  configurable: true,
  enumerable: false,
  writable: true,
  value: 'a_school'
});

var p1 = new Person();

Object.defineProperty(p1, 'name', {
  configurable: true,
  enumerable: true,
  writable: true,
  value: 'test'
});

Object.defineProperty(p1, 'age', {
  configurable: true,
  enumerable: false,
  writable: true,
  value: 20
});


for(var prop in p1){
  console.log(prop);
} // name, grade

                    
console.log(Object.keys(p1));                   // name

console.log(Object.getOwnPropertyNames(p1));    // name, age


console.log(p1.hasOwnProperty('name'));    // true

console.log(p1.hasOwnProperty('age'));     // true

console.log(p1.hasOwnProperty('grade'));   // false

console.log(p1.hasOwnProperty('school'));  // false

Here is a summary of which method displays which properties:

Methods Prototype Object Instance Object
Enumerable Not Enumerable Enumerable Not Enumerable
for...in
Object.keys()
Object.getOwnPropertyNames()
hasOwnProperty()
← JavaScript configurable JavaScript the value of this inside closure →
 
comments powered by Disqus