Difference between var and this in Javascript functions?

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.

Leave a Comment