Search code examples
javascriptecmascript-6ecmascript-5

es6 propertyIsEnumerable


Public methods created through es6 class syntax are not enumerable. What is the difference between 'getname' method written in es5 & es6?

function Cat(){
 this.name="cat"
}
Cat.prototype.getname = function() {return this.name}
var cat = new Cat()

class Dog { 
 constructor(){
   this.name="dog"
 } 
 getname() {
   return this.name
 } 
}
var dog = new Dog()

cat.__proto__.propertyIsEnumerable("getname") //true
dog.__proto__.propertyIsEnumerable("getname") //false

Solution

  • Adding a property directly to an object with obj.property = foo will always create an enumerable property.

    The ES2015 class syntax doesn't do that.

    To (partially) replicate the ES2015 functionality in ES5 you'd have to add the getname method using Object.defineProperty(Cat.prototype, 'getname', ...)