0

In the following code, the line obj.sayhello() means that sayhello executes in the context / scope of obj. str is not defined (via var) in the sayhello method. JS will look up the variable in the scope i.e. in the obj which clearly has a str property. Why does the script throw a ReferenceError?

Uncaught ReferenceError: str is not defined at Object.sayhello

var obj = {
    str: "hello",
    sayhello: function(){
      return str;
    }
  };

obj.sayhello();
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
appu
  • 127
  • 1
  • 9
  • 1
    `str` is not a variable but an object property. You have to access it using `this` --`this.str` will yield the correct value. – Krishna Prashatt Aug 08 '19 at 08:16
  • Strongly related: [Self-references in object literals / initializers](/q/4616202/4642212) — this has the exact opposite problem, but causes a similar error. In that question, `this` is used, but not `function`; here, it’s the other way around. I’d consider those to be distinct enough that this shouldn’t be closed as a duplicate. Also related: [var vs this in Javascript object](/q/4946625/4642212). – Sebastian Simon Sep 19 '21 at 05:51

2 Answers2

1

since you're in the obj scope, you should return this.str.

str by itself is not a variable in its plain definition, its a property of an object. Hence, you cannot simply access str but you have to access something.str. If outside the object, this would be obj.str, if inside the object- this.str.

Gibor
  • 1,695
  • 6
  • 20
0

For reference to same object you need to use a this, return str; => return this.str;

var obj = {
    str: 'hello',
    sayhello: function (){ return this.str; } // <==
}

obj.sayhello()
Maksym Petrenko
  • 1,053
  • 1
  • 6
  • 15