问题描述
假设我有:
var myNamespace = {
_prop1: 'hello',
_prop2: _prop1 + ' you!'
};
我现在发现这在加载时在_prop2
上会出错.
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.
推荐答案
尝试设置prop2时,对象尚未初始化,因此prop1和mynamespace的值均未定义.
When you try and set prop2 the object hasn't initialised so the value of prop1 and mynamespace are both undefined.
有两种方法可以实现所需的功能,一种方法是将prop2创建为一个函数,以便它可以动态获取prop1的值
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!' }
};
另一种方法是在myNamespace初始化之后设置prop2
Another way would be to set prop2 after myNamespace has been initialised
这篇关于Javascript,并从另一个引用一个名称空间属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!