1

I am a newbie to javascript learning objects. I created an object here is the code

const address = {
    street: "",
    city: "",
    zipcode: "",
    showAddress: function() {
        return (street+city+zipcode);
    }
};

when I type:

address.showAddress();

It shows the error:

"Uncaught ReferenceError: street is not defined
    at Object.showAddress (index.js:237)
    at <anonymous>:1:

9"

I just googled the error and couldn't find a solution. at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined I couln't understand why this error is happening in this scope. at developer .mozilla.org it is written that function can access all variables and functions defined inside the scope in which it is defined.

The question is:

why the member function can't access properties of it's own object. I studied oop concepts in javascript and there I can access properties of object easily by it's own method. I hope that the questio is clear.

Kashif Ghafoor
  • 306
  • 2
  • 10
  • You can use `this.street` etc... without the `this` the function tries to look for a variable called street in the surrounding scope rather than looking at the properties on your object that called your `showAddress()` method – Nick Parsons Sep 19 '21 at 04:36
  • _“it is written that function can access all variables and functions defined inside the scope in which it is defined”_ — Correct. There are no variables called `street`, `city`, and `zipcode`. Those other things are object properties. – Sebastian Simon Sep 19 '21 at 04:42
  • 1
    thank your @NickParsons I got it. – Kashif Ghafoor Sep 19 '21 at 04:45
  • Related: [Reference Error for property of Javascript Object](/q/2662297/4642212) – Sebastian Simon Sep 19 '21 at 04:56
  • Duplicate target found by [Googling _site:stackoverflow.com js ReferenceError in object method referring to properties_](//google.com/search?q=site%3Astackoverflow.com+js+ReferenceError+in+object+method+referring+to+properties). That took a while to find, though, because it’s overshadowed by the more common error of trying to _use_ `this`, but _not_ in a function… – Sebastian Simon Sep 19 '21 at 05:19

1 Answers1

0

try this

You have to use a 'this' to use inside the key. If I'm right the only way is to use 'this'. Check the picture and write me if it work.

const address = {
street: "a",
city: "b",
zipcode: "c",
showAddress: function() {
    return (this.street+this.city+this.zipcode);
}

};

Alex Choi
  • 144
  • 7