简体   繁体   中英

How to communicate different levels in the same javascript object

I am trying to namespace my jQuery app.

Example:

var app = {
    data : {
     data1: ''
   },
   fn: {
    setData1: function(value){
      app.data.data1 = value
    }
  }  
}

This works, but is there a better solution which doesn't use the full path? Moreover, is this a good code structure for a medium-sized application?

Javascript does not have syntax for specifying shortcuts to a parent element in a nested literal object definition. And, in fact, Javascript a nested object inside another object could have been defined anywhere and the reference assigned into the object and could be assigned into many objects so there is no real such thing as a parent at runtime as far as Javascript is concerned. Javascript just doesn't work that way.

As such, if you want to reference another element of the object that is not below it, then you will have to use the full path of object names starting from the top of the object.

As to whether this is a good way to do this, that is entirely context-specific. At first glance (and with no other context supplied), I don't see why you need the fn or data levels in your object. Data properties and methods can be at the same level and that is commonly done without adding extra levels. You will find that extra levels that aren't necessary just increase the amount of typing in your code and do not improve performance. You should give your methods and data properties meaningful enough names that it's very clear what they are and what they are used for. A name like data1 is not a particularly good example.

In addition, there is generally not a reason to make a setData1() method for a public data1 property, but if you put them at the same level, you can do use the this pointer in the method which will be set to app if someone calls app.setData1() :

var app = {
     data1: ''
     setData1: function(value){
          this.data1 = value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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