Difference between var and this in Javascript functions?

var tools = {};

tools.triangle = function() {
    var originX = 0;
    var originY = 0;
}

 

var tools = {};

tools.triangle = function() {
    this.originX = 0;
    this.originY = 0;
}

Are there any differences between these two code blocks? Sorry if this has been asked before.


var creates a local variable within tools.triangle. The variables originX and originY cannot be interacted with outside of tools.triangle. this is a pointer to the current object you are dealing with. The second example can be used to give properties to an object by doing new tools.triangle();. If you do not use new and just use tools.triangle();, this will point the global object which is the window object. You can change the object to which this points by using the function methods call(); and apply(); like this:

var myObj = {};

tools.triangle.call( myObj );

// "this" in tools.triangle now points to myObj
// myObj now has the properties originX and originY

It is important to know that this can reference any object, as well as be undefined or null in ES5 strict mode.

You can find more information here.


In the first example, X and Y both exist as local variables to the closure saved in the variable triangle.

In the second example, X and Y exist as variables to the object tools.triangle because of the use of this.