Difference between 'this' and normal variable declaration - javascript

What is the difference between declaring a variable with this in my function than declaring normally using let or var?
const controller = (function() {
this.name = 'John';
})();
const controller2 = (function() {
let name = 'Mary';
})();

this inside your function is window object. So you are not creating a variable, you are adding a property to the window object
console.log((function(){return this})() === window)

Related

Access global variable with same name as instance variable

var myVar = 5;
var example = function() {
var myVar = 10;
// How can I access the global variable 10?
};
If there is a global variable with the same name as a local variable, how can I access the global one?
I am not using es6.
I am running it in jsdb, not a browser or node so I do not have access to objects 'Window' or 'global'
Assuming you can alter the code calling your example() function, you should be able to pass the current scope using Function.prototype.call() and access it using this. For example
'use strict'
var myVar = 5;
var example = function() {
var myVar = 10;
console.info('Local:', myVar)
console.info('Outer:', this.myVar)
};
example.call({ myVar })

How can we get the execution context of a function?

Let say we declare a variable in the global context, like so:
var someVariable = "someValue";
We can always access its value like window['someVariable'] as it is in the global execution context.
But, how can we access it value the same way if it is inside some function and not in the global execution context? For e.g.
function someFunction(someParameter) {
var someVariable = "some value";
// some code
}
I want to do something like someFucntionContext['someParameter'] or someFucntionContext['someVariable'] to access the value of those variables in the execution context of the someFucntion like I just did for the variable declared in the global context.
That's not possible without returning objects or instantiating the function and accessing the property.
Global variables are automatically a property of the window object, provided you use var and not let or const. Such as root level functions being automatically a method of the window object. But functions do not behave like primitive objects. You need to do something like
function Favorites(){
return{
food: "burrito",
color: "gray"
}
}
var fav = Favorites();
var favfood = fav.food; //fav['food']
OR
function Favorites(){
this.food = "burrito";
this.color = "gray";
}
var fav = new Favorites();
var favfood = fav.food; //fav['food']
And like so
var favfood = window.fav.food;
var favcolor = window['fav']['color']
One of the approach could be exposing certain properties of the function itself.
function fn(){
fn.num = 100;
}
//access fn.num
console.log(fn["num"])
You can control which properties you want to expose from the function itself. For example,
function doSomething(num, addStr){
//expose num
doSomething.num = num;
var str = "Hello ";
if(addStr){
str += addStr;
}
//expose str
doSomething.str = str;
}
//set num
doSomething(100);
//access num
console.log(doSomething.num)
console.log(doSomething["num"])
//set num and str
doSomething(200, "Jerry!")
//access str
console.log(doSomething["str"])

Javascript Variable Declaration: this versus var

Is there a difference between
function test(){
var myVar;
}
and
function test(){
this.myVar;
}
The value of this is determined by how function is called whereas var VARIABLE_NAME will create a variable in the local-scope of the function.
In second example, you are creating Object-Constructor using which you can create many instances of the test object using new operator
function test(name) {
this.name = name;
}
console.log(new test('Abc'));
console.log(new test('Xyz'));
There are two scopes in javascript , local or function scope and global scope .
In your case this is global and var is local scope/function scope .
If you use this inside IIFE (immediate invoking function expression)and 'use strict' its not global
The most difference is that your first code works like a private property (local scope) and the second is like a public property (global scope).
Examples:
var test = function(){
this.myVar = "test var";
}
var test2 = function() {
var myVar = "test2 var";
}
alert((new test()).myVar);
alert((new test2()).myVar);

global objects and passing by reference

I have a global variable 'globalProperty' and assign it to a property of an object'.
var globalProperty = 'hello';
function func1(){
obj['prop'] = globalProperty;
//code....
obj['prop'] = 'good'.
}
I want my obj[prop] to reference the global variable. SO if I modify the obj[prop], the global variable will also be modified to 'good'.
javascript always use by value for passing params, you can still create a global object and modify its properties , for example
var globalObject= new Object();
globalObject.text = 'Hello';
function func1() {
obj = {};
obj['prop'] = globalObject;
console.log(globalObject.text);
obj['prop'].text = 'good';
console.log(globalObject.text);
}
func1();

Declaring variables with this or var?

What is the difference between declaring a variable with this or var ?
var foo = 'bar'
or
this.foo = 'bar'
When do you use this and when var?
edit: is there a simple question i can ask my self when deciding if i want to use var or this
If it is global code (the code is not part of any function), then you are creating a property on the global object with the two snippets, since this in global code points to the global object.
The difference in this case is that when the var statement is used, that property cannot be deleted, for example:
var foo = 'bar';
delete foo; // false
typeof foo; // "string"
this.bar = 'baz';
delete bar; // true
typeof bar; "undefined"
(Note: The above snippet will behave differently in the Firebug console, since it runs code with eval, and the code executed in the Eval Code execution context permits the deletion of identifiers created with var, try it here)
If the code is part of a function you should know that the this keyword has nothing to do with the function scope, is a reserved word that is set implicitly, depending how a function is called, for example:
1 - When a function is called as a method (the function is invoked as member of an object):
obj.method(); // 'this' inside method will refer to obj
2 - A normal function call:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
3 - When the new operator is used:
var obj = new Constructor(); // 'this' will refer to a newly created object.
And you can even set the this value explicitly, using the call and apply methods, for example:
function test () {
alert(this);
}
test.call("hello!"); //alerts hello!
You should know also that JavaScript has function scope only, and variables declared with the var statement will be reachable only within the same function or any inner functions defined below.
Edit: Looking the code you posted to the #David's answer, let me comment:
var test1 = 'test'; // two globals, with the difference I talk
this.test2 = 'test'; // about in the beginning of this answer
//...
function test4(){
var test5 = 'test in function with var'; // <-- test5 is locally scoped!!!
this.test6 = 'test in function with this'; // global property, see below
}
test4(); // <--- test4 will be called with `this` pointing to the global object
// see #2 above, a call to an identifier that is not an property of an
// object causes it
alert(typeof test5); // "undefined" since it's a local variable of `test4`
alert(test6); // "test in function with this"
You can't access the test5 variable outside the function because is locally scoped, and it exists only withing the scope of that function.
Edit: In response to your comment
For declaring variables I encourage you to always use var, it's what is made for.
The concept of the this value, will get useful when you start working with constructor functions, objects and methods.
If you use var, the variable is scoped to the current function.
If you use this, then you are assigning a value to a property on whatever this is (which is either the object the method is being called on or (if the new keyword has been used) the object being created.
You use var when you want to define a simple local variable as you would in a typical function:-
function doAdd(a, b)
{
var c = a + b;
return c;
}
var result = doAdd(a, b);
alert(result);
However this has special meaning when call is used on a function.
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
doAdd.call(o, a, b);
alert(o.c);
You note the first parameter when using call on doAdd is the object created before. Inside that execution of doAdd this will refer to that object. Hence it creates a c property on the object.
Typically though a function is assigned to a property of an object like this:-
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
o.doAdd = doAdd;
Now the function can be execute using the . notation:-
o.doAdd(a, b);
alert(o.c);
Effectively o.doAdd(a, b) is o.doAdd.call(o, a, b)
var foo = 'bar'
This will scope the foo variable to the function wrapping it, or the global scope.
this.foo = 'bar'
This will scope the foo variable to the this object, it exactly like doing this:
window.foo = 'bar';
or
someObj.foo = 'bar';
The second part of your question seems to be what is the this object, and that is something that is determined by what context the function is running in. You can change what this is by using the apply method that all functions have. You can also make the default of the this variable an object other than the global object, by:
someObj.foo = function(){
// 'this' is 'someObj'
};
or
function someObj(x){
this.x=x;
}
someObj.prototype.getX = function(){
return this.x;
}
var myX = (new someObj(1)).getX(); // myX == 1
In a constructor, you can use var to simulate private members and this to simulate public members:
function Obj() {
this.pub = 'public';
var priv = 'private';
}
var o = new Obj();
o.pub; // 'public'
o.priv; // error
Example for this and var explained below:
function Car() {
this.speed = 0;
var speedUp = function() {
var speed = 10; // default
this.speed = this.speed + speed; // see how this and var are used
};
speedUp();
}
var foo = 'bar'; // 'var can be only used inside a function
and
this.foo = 'bar' // 'this' can be used globally inside an object

Categories

Resources