panda
panda

Reputation: 1344

var name = new object() vs this.name = new object

In this case, I define an object called DropHandler

function DropHandler(){}
DropHandler.prototype={
    AllowDrop : AllowDrop,
    Drag : Drag,
    Drop : Drop
}

And want to create an instance of DropHandler in Admin object.But what is the different between the following code? code (2) seems can not be used in this case, it will get a undefined type error

var BackendAdmin = function(){
    this.DropHandler = new DropHandler();//(1);
    var DropHandler = new DropHandler();//(2);
}

Upvotes: 0

Views: 276

Answers (2)

zerkms
zerkms

Reputation: 254896

The difference is that in (1) you assign new DropHandler object to DropHandler property of BackendAdmin instance, and in (2) you assign it to a local DropHandler variable.

You get error because var is moved to the top of the method automatically (it is called Hoisting) by the interpreter and your code in fact looks like:

var BackendAdmin = function(){
    var DropHandler;
    this.DropHandler = new DropHandler();//(1);
    DropHandler = new DropHandler();//(2);
}

So you try to call the function, which is actually overwriten by an empty variable.

PS: cannot find really good explanation of JS variables hoisting, but this is something from google: http://blog.binarymist.net/2011/11/14/scoping-hoisting-in-javascript/

Upvotes: 3

jfriend00
jfriend00

Reputation: 707218

You can't have two separate entities (a local variable and a function in scope) with the same name and have them still be seprately reachable entities.

When you create the local variable, it temporarily overrides/hides the function of the same name in that scope and that function name is no longer accessible in that scope. Change the name of either one and it should work like this:

var BackendAdmin = function(){
    this.DropHandler = new DropHandler();//(1);
    var myDropHandler = new DropHandler();//(2);
}

this.DropHandler works because in that case DropHandler is a property on another object and thus separate from the DropHandler() function.

Upvotes: 1

Related Questions