简体   繁体   English

如何在另一个键/值对中使用定义的键

[英]How can I use defined key in another key/value pair

I have this javascript object: 我有这个javascript对象:

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

But, it returns an error that says AccDocs is not defined . 但是,它返回一个错误,指出AccDocs is not defined
How can I achieve something like this? 我怎样才能实现这样的目标?

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关键字访问它:

this.query();

Keeping in mind that the value of this will vary depending on how the function is called (when abcdAccDocs.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). 该值牢记this取决于该函数是如何被调用时( abcdAccDocs.deleteAndQuery()被调用, this里面deleteAndQueryAccDocs ,因为它是第一个对象到最后的左边. ,但如果你是到第一个副本query到另一个变量,然后调用query()它传递给setTimeout ,或者如果你使用callapply则价值this将改变)。

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

By using the this keyword: 通过使用this关键字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM