Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 762
Ryan Peschel Avatar asked Jul 01 '12 22:07

Ryan Peschel


People also ask

What is var and function in JavaScript?

The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global.

What is the difference between VAR and without VAR in JavaScript?

Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it. Global variables are destroyed when you close the page. If you declare a variable, without using "var", the variable always becomes GLOBAL.

Whats the difference between a function and a variable?

Remember that variables are items which can assume different values. A function tries to explain one variable in terms of another.

Do I need VAR in JavaScript?

The var keyword is never "needed". However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window object).


1 Answers

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.

like image 53
David G Avatar answered Oct 24 '22 20:10

David G