0

So, I have this piece of code:

const test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
  something: this.prop,
};

console.log(test.func());
// expected output: 42, which we are getting. But...

console.log(test.something);
// expected output: 42, here the output is `undefined`.

I want that something to be the prop property of the same object. And the function propery gives the value back, but when I log the something property it gives undefined. I tried this in the node.js and in the browser too.

Why is this happening and can somebody get this to work please?

Blaze_droid
  • 479
  • 4
  • 13
  • [How does the “this” keyword in Javascript act within an object literal?](/q/13441307/4642212). Also, everything there is to know about `this` is explained in [How does the “this” keyword work?](/q/3127429/4642212). – Sebastian Simon Jul 07 '21 at 07:10

3 Answers3

1

This can be achieved using getter and setter of javascript object properties.

For example in your case:

const test = {
  prop: 42,
  get getProp() {
    return this.prop;
  },
};

You can get the value of prop using

test.getProp
bill
  • 118
  • 5
1

It's a matter of invocation context: in test.func(), this context is test and console returns correctly 42. In something, this context is the window (that doesn't have any idea of what is this.prop) and console returns undefined. That's because:

In JavaScript the value of this not refer to the function in which it is used or it’s scope but is determined mostly by the invocation context of function (context.function()) and where it is called.

Source

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
1

The reason you're getting undefined in the second console.log is because this refers to something instead of the object test.

This is due to the invocation context which in the first case is test where in the second case is something.

The invocation context is determind before the .

Ran Turner
  • 14,906
  • 5
  • 47
  • 53