0

In the following code, the function MakeNode() returns a node, containing the arguments provided to MakeNode(). Within the node, there is a function, an arrow function that requires one of the variables of the node.

I have read the ES6 js doc regarding this. and scopes. Still can't find how my function can access the variable from its own object.

I Have tried accessing it these ways:

this.x
this.X
x
X
n.x
n.X

No success. Actual code:

    function MakeNode(x, y) {
      let n =
      {
        Parent: null,
        X: x,
        Y: y,
        PrintXY: () => {
          console.log("X, Y =", x, y);
        }
      }
      return n;
    }
    
    //further, when called:
    var aNode = MakeNode(10, 20);
    aNode.PrintXY();

I expect the print statement to be

X, Y = 10 20

But i get:

X, Y = undefined undefined

I also get the following error, no matter what way i try to access it:

TypeError: Cannot read property 'X' of undefined
Lucien
  • 9
  • 4
  • 5
    Your actual code does exactly what you say you want. (Not that the object has anything to do with the variables you are accessing, its a simple closure). – Quentin Jul 11 '19 at 15:56
  • What environment are you using? – Geeky Guy Jul 11 '19 at 15:58
  • @Quentin yeah, i just ran the code snipet and it seems to work. This must be explained by me not summarising every detail required for this example. The actual code is a little more complexe, but ill try giving more details, more pertinent lines of codes. – Lucien Jul 11 '19 at 16:02
  • Always **test** your [mcve] to make sure they actually demonstrate the problem. Using a live demo is helpful for that. – Quentin Jul 11 '19 at 16:03
  • You are right. this is my very first post. Should I remove the post and create another one when my minimal reproducible example will be more representative of my issue here? – Lucien Jul 11 '19 at 16:06
  • No, fix the existing question. Destroying history and asking duplicate questions is looked on unfavourably (and can lead to a question ban) – Quentin Jul 11 '19 at 16:09
  • Found it. I had variables declared in the wrong order, in a section of my code i hadn't touch in days. Some of these required others to be properly defined. Thank you for your help people, I will now close this question. Have a good day. – Lucien Jul 11 '19 at 17:45

0 Answers0