0

I have read the documentation for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Why can't we directly access this.prop, but rather we have to write a function just to return this.prop?

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

console.log(test.func());
// expected output: 42

console.log(test.directAccess);
// expected output: 42
// actual output: undefined
t.c
  • 623
  • 5
  • 19

2 Answers2

3

It's all about context, at the time you're constructing the object test , the this context is the parent scope which is creating the object.

When invoking the function, your scope is now that of test which at that point does have a property of prop.

Dan D
  • 2,493
  • 15
  • 23
0

You can directly access prop. However, the way to do that is to use test.prop.

In JavaScript, this is a special variable that is set to the "receiver" of a function call, meaning the object to the left of the dot. When you write

test.func()

then test is the receiver, so this points to test inside the function.

In the case of directAccess, there is no function. The expression this.prop is evaluated at the time test is defined. At this point, this is probably the JavaScript default object, which does not have a property called prop, so you get undefined.

You might be used to Java, in which this inside a class always refers to an instance of the class itself. It doesn't work that way in JavaScript.

Willis Blackburn
  • 8,068
  • 19
  • 36