问题
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