Javascript and referencing one namespace property from another [duplicate]

本小妞迷上赌 提交于 2019-12-24 13:56:01

问题


Possible Duplicate:
How can a Javascript object refer to values in itself?

Let's say I have:

var myNamespace = {
      _prop1: 'hello',
      _prop2: _prop1 + ' you!'
};

I'm just now finding out that this will error on _prop2 at load.

I can't understand why this doesn't work, I've worked around it in my code but I would still like to understand.


回答1:


When you try and set prop2 the object hasn't initialised so the value of prop1 and mynamespace are both undefined.

There are a couple of ways to achieve what you want, one way would be to create prop2 as a function so it can dynamically get the value of prop1

var myNamespace = {
      _prop1: 'hello',
      _prop2: function(){ return this._prop1 + ' you!' }
};

Another way would be to set prop2 after myNamespace has been initialised




回答2:


You have to use this:

var myNamespace = {
    _prop1: 'hello'
};
myNamespace._prop2: myNamespace._prop1 + ' you!';



回答3:


Well, you can do

var myNamespace = {
      _prop1: 'hello',
      _prop2: myNamespace._prop1 + ' you!'
};

I don't think it's possible to do it any other way in the declaration (eg: using "self" or "this" doesn't work)



来源:https://stackoverflow.com/questions/14553639/javascript-and-referencing-one-namespace-property-from-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!