0

I have this javascript object:

return {
   AccDocs: {
      query: function() {
         ...
      },
      deleteAndQuery: function() {
         ...
         AccDocs.query(); //Error: AccDocs is not defined
      }
   }
}

But, it returns an error that says AccDocs is not defined.
How can I achieve something like this?

Mehdi Hoseini
  • 347
  • 1
  • 3
  • 9
  • By the way you are going to create `circular reference `. – ozil Feb 08 '16 at 08:11
  • 1
    @ozil — That won't create a circular reference, and even if it did: so what? There's no sign that any code is going to be trying to process it recursively. – Quentin Feb 08 '16 at 09:07

2 Answers2

2

Variables and properties on objects are different things. You cannot access the property of an object without specifying which object you mean.

You can probably access it using the this keyword:

this.query();

Keeping in mind that the value of this will vary depending on how the function is called (when a.b.c.d.AccDocs.deleteAndQuery() is called, this inside deleteAndQuery will be AccDocs as it is the first object to the left of the last ., but if you were to first copy query to another variable and then call query(), pass it to setTimeout, or if you were to use call or apply then the value of this would change).

For more robustness (but less flexibility, since being able to change the context can be useful) you can store your object in a variable which you can access by name.

var AccDocs = {
    query: function() {
            ...
    },
    deleteAndQuery: function() {
            ...
        AccDocs.query();
    }
};

return { AccDocs: AccDocs };
Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1

By using the this keyword:

return {
   AccDocs: {
      query: function() {
         ...
      },
      deleteAndQuery: function() {
         ...
         this.query(); //Here
      }
   }
}
Poul Kruijt
  • 58,329
  • 11
  • 115
  • 120
  • @RomanPerekhrest — Of course it will return undefined, there is no return statement in it. I suspect you mean that the value of `this.query` will be undefined. It's possible, but depends on how the function gets called. Given the most likely code for calling it, it will work just fine and `this` will be the value of the `AccDocs` property. – Quentin Feb 08 '16 at 09:04
  • The typical case being when you call `something.AccDocs.deleteAndQuery()` (as opposed to, for instance, `something.AccDocs.deleteAndQuery.call(something)`) – Quentin Feb 08 '16 at 09:11