Pranesh Ravi Pranesh Ravi - 20 days ago 12
Javascript Question

Object.defineProperty() inside the getter

I've a scenario where I need to modify a

property
of a
class
using
Object.defineProperty()
. I know it can be done through the
get()
of the
descriptor
.

If you see the example below, I'm trying to return a
function
which when called will return a value from
this
.

My question is, do I need to
define
that
property
again for the
this
object? Is it necessary? If yes, why?

When I define a property to a class,
this
will also reflect the same right?

I came through this and I'm curious to know why he is doing this.



class A {
constructor() {
this.h = 'hello world'
}
hello() {}
}

const des = Object.getOwnPropertyDescriptor(A.prototype, 'hello')

Object.defineProperty(A.prototype, 'hello', {
configurable: true,
get: function(){
//is this necessary
Object.defineProperty(this, 'hello', {
configurable: true,
value: () => this.h,
})
//
return () => this.h
}
})

const n = new A()

console.log(n.hello())




Answer

I have no idea why that person is doing this. I probably wouldn't do it. But if your question is whether there is a difference in doing it or not, the answer is yes.

class A {
  constructor() {
    this.h = 'hello world'
  }
  hello() {}
}
const des = Object.getOwnPropertyDescriptor(A.prototype, 'hello')
Object.defineProperty(A.prototype, 'hello1', {
  configurable: true,
  get: function() {
    Object.defineProperty(this, 'hello1', {
      configurable: true,
      value: () => this.h,
    });                 
    return () => this.h;
  }
});
Object.defineProperty(A.prototype, 'hello2', {
  configurable: true,
  get: function() {
    return () => this.h;
  }
});
const n = new A()
console.log(n.hello1); // () => this.h       OK
console.log(n.hello2); // () => this.h       OK
Object.setPrototypeOf(n, null);
console.log(n.hello1); // () => this.h       Still OK
console.log(n.hello2); // undefined          Oops!

It's also possible that calling a getter may be more expensive than reading a data property.