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.
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.
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.
Remember that variables are items which can assume different values. A function tries to explain one variable in terms of another.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With