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?

2
  • By the way you are going to create circular reference . Commented Feb 8, 2016 at 8: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. Commented Feb 8, 2016 at 9:07

2 Answers 2

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 };
Sign up to request clarification or add additional context in comments.

1 Comment

damn it. Ok, you won today. I'll delete my post. Today - is not my lucky day
1

By using the this keyword:

return {
   AccDocs: {
      query: function() {
         ...
      },
      deleteAndQuery: function() {
         ...
         this.query(); //Here
      }
   }
}

2 Comments

@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.
The typical case being when you call something.AccDocs.deleteAndQuery() (as opposed to, for instance, something.AccDocs.deleteAndQuery.call(something))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.