Home Ask Login Register

Developers Planet

Your answer is one click away!

Mehdi Hoseini February 2016

How can I use defined key in another key/value pair

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?

Answers


PierreDuc February 2016

By using the this keyword:

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


Quentin February 2016

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 };

Post Status

Asked in February 2016
Viewed 2,849 times
Voted 4
Answered 2 times

Search




Leave an answer


Quote of the day: live life