使用命名空间实例化对象时有一个非常奇怪的问题。
如果我尝试这样做,它将无效:
this.myView = new this.getApp().Views.SubView({ // it doesn't work
initialize: function () {
console.log('bouh');
}
});
但是,如果我尝试这样做,它会起作用:
this.myView = new (this.getApp().Views).SubView({ // it works
initialize: function () {
console.log('bouh');
}
});
您可以在此处查看示例:http://jsfiddle.net/queval_j/a0yr41mn/
此类代码以前一直在运行,并且从上周开始。我必须更新我的代码,因为这个新的行为..所以,这是JS编译器的问题还是我一段时间以来都很幸运?
答案 0 :(得分:1)
所有关于优先权 在失败的行
this.myView = new this.getApp().Views.SubView({ // Doesn't work ?!
new运算符作为构造函数在this.getApp函数上运行,并且构造函数尝试访问成员' __pages
'这里是null,然后访问子成员' app
'会失败
在工作线上
this.myView = new(this.getApp().Views).SubView({
括号为新运算符提供this.getApp().Views
优先级,因此首先对其进行求值,然后返回SubView
,然后由new
运算符
可能的整洁解决方法是在{/ p>之类的变量中获取this.getApp().Views
的值
var AppViews = this.getApp().Views;
然后直接使用变量
this.myView = new AppViews.SubView({