shubham AK
shubham AK

Reputation: 292

Object define property with class

Here I'm trying to explore more about object properties using Object.getOwnPropertyDescriptor. But when I used the not-static method I'm getting nothing in response. I don't know what is the reason behind this.

When I use getName method non-static output - undefined

class abc {
    getName() {
    return 'abc class name'
  }
}

console.log(Object.getOwnPropertyDescriptor(abc, 'getName'))

When I use getName method static output - Object {writable: true, enumerable: false, configurable: true}

class abc {
    static getName() {
    return 'abc class name'
  }
}

console.log(Object.getOwnPropertyDescriptor(abc, 'getName'))

Upvotes: 1

Views: 1118

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138235

Cause non-static methods are part of the prototype:

Object.getOwnPropertyDescriptor(abc.prototype, 'getName')

As you know, class syntax is just syntactic sugar for:

function abc(){
  //the constructor goes here
}

abc.someStatic = 1;

abc.prototype = {
  getName(){
    //...
  }
};

Upvotes: 1

hackerrdave
hackerrdave

Reputation: 6706

This is because in your first scenario, getName() is an instance of method of objects that are of type abc:

let a = new abc();
a.getName() //'abc class name'

In your second scenario, using the static keyword you are creating a class method:

abc.getName() //'abc class name'

Only in the second scenario is getName set as an ownProperty for abc. In the first scenario, getName is available on the prototype.

Upvotes: 3

Related Questions