queval_j
queval_j

Reputation: 188

Create new object by using namespace

I have a very strange problem to instantiate an object by using namespace.

If I try to do this, it will not work :

this.myView = new this.getApp().Views.SubView({ // it doesn't work
     initialize: function () {
        console.log('bouh');
     }
});

But, If I try to do that, it will work :

this.myView = new (this.getApp().Views).SubView({ // it works
     initialize: function () {
        console.log('bouh');
     }
});

You can see an example here : http://jsfiddle.net/queval_j/a0yr41mn/

This kind of code has been working previously, and since the last week. I have to update my code because of this new behavior.. So, is it a problem from the JS Compiler or have I been lucky since a while ?

Upvotes: 0

Views: 34

Answers (1)

mfarouk
mfarouk

Reputation: 654

it is all about precedence in the failing line

this.myView = new this.getApp().Views.SubView({ // Doesn't work ?!

the new operator works on this.getApp function as the constructor, and as the constructor tries to access member '__pages' which is here is null , then accessing sub member 'app' will fail

while in the working line

 this.myView = new(this.getApp().Views).SubView({

the parenthesis gives the this.getApp().Views precedence over the new operator, so it is evaluated first, then return SubView which is then treated as the constructor by new operator

possible neat workaround for this is to get the value of this.getApp().Views in a variable like

 var AppViews = this.getApp().Views;

then use the variable directly

this.myView = new AppViews.SubView({

jsFiddle updated

Upvotes: 1

Related Questions