[英]How to communicate different levels in the same javascript object
I am trying to namespace my jQuery app.我正在尝试命名我的 jQuery 应用程序。
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. Javascript 没有用于指定嵌套文字对象定义中父元素的快捷方式的语法。 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 另一个对象中的嵌套对象可以在任何地方定义,并且引用分配给该对象并且可以分配给许多对象,因此就 Javascript 而言,在运行时没有真正的父级这样的东西。 Javascript just doesn't work that way.
Javascript 不能那样工作。
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.乍一看(并且没有提供其他上下文),我不明白为什么您需要对象中的
fn
或data
级别。 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.像
data1
这样的名称并不是一个特别好的例子。
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()
:另外,一般没有理由为一个公共的
data1
属性创建一个setData1()
方法,但是如果你把它们放在同一层,你可以在方法中使用this
指针,如果有人的话,它会被设置为app
调用app.setData1()
:
var app = {
data1: ''
setData1: function(value){
this.data1 = value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.