"this" refers to "window" object not working as expected [duplicate] - javascript

This question already has answers here:
Do let statements create properties on the global object?
(5 answers)
Closed 2 years ago.
I experimented a bit with this keyword and I found a strange problem. When a variable is declared as var then this correctly refer to this variable. But if i declared the same variable as let or const then this lost reference and show undefined in console.
var prop = "outer"; // not working if let or const.
let foo = {
prop: "inner",
show() {
console.log(this.prop)
}
}
let a = foo.show;
let b = foo.show.bind(foo);
a()
b()

When you run this code outside of strict mode (as here), then the this keyword defaults to the global object - which in the browser is window. (In strict mode it would be undefined so a() will throw an error.)
The difference in behaviour between var and let/const is a simple consequence of the fact that var-declared global variables are the same thing as properties on the global (window) object, whereas that doesn't happen with variables (even global ones) declared with let or const.
See for example MDN:
Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

Related

Variable declared with let or const do not become direct property of `window` object in chrome console, why? [duplicate]

This question already has answers here:
why don't const and let statements get defined on the window object [duplicate]
(2 answers)
Closed 2 months ago.
In the chrome console, when I declare variables with let or const these DO NOT become the property of window object. However, the variable declared with var DO becomes the direct property of the window object in the chrome console. For e.g:
let sayHi = 'Hi'
const greet = 'Good Morning'
var sayHola = 'Hola Hola'
window.hasOwnProperty('sayHi') //false
window.hasOwnProperty('greet') //false
window.hasOwnProperty('sayHola') //true
Then what are the actual scopes/object of a variable declared with let or const in the chrome console?
All variables (whether declared with var, const, or let) declared in the console are global by default, but being a property of the window object is not the same as having global scope.
This actually isn't just something that happens in the console, variables defined with let and const never are set as properties to window. See this snippet:
let sayHi = 'Hi';
const greet = 'Good Morning';
var sayHola = 'Hola Hola';
console.log(window.hasOwnProperty('sayHi')); // => false
console.log(window.hasOwnProperty('greet')); // => false
console.log(window.hasOwnProperty('sayHola')); // => true
This behavior is intentional and is set out by the standard. It allows for better isolation of variables to specific scopes and no meddling from outside that scope.

Javascript global scope with const vs var [duplicate]

This question already has answers here:
A javascript 'let' global variable is not a property of 'window' unlike a global 'var' [duplicate]
(1 answer)
Do let statements create properties on the global object?
(5 answers)
Closed 5 years ago.
var name = 'John';
console.log(this.name, document.name, window.name, name);
const meme = "Bruce";
console.log(this.meme, document.meme, window.meme, meme);
Output:
John undefined John John
undefined undefined undefined "Bruce"
Is global scope differently defined for var and const? I thought the only difference would be the const is immutable.
Yes, window scope and variables defined using var is different from the scope of variables declared using const and let.
See also Is it possible to delete a variable declared using const?, Why does .then() chained to Promise.resolve() allow const declaration to be reassigned?

Difference between local and global variables in javascript? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 6 years ago.
I noticed that in JavaScript, Inside a function some times a variable created without mentioning var before it.
For example :
function myfunction() {
x = 10;
var y = 10;
}
what is the difference between these both?
function myact() {
x = 20;
var y = 10;
console.log(x);
console.log(y);
}
myact();
console.log(x);
//y not available here
var is used for declaration. So, assigning without declaration will simply give it global scope meaning: it will first search if it is available in any scope stack above, if not creates the variable implicitly in global scope and assigns.
JS Docs says:
The scope of a variable declared with var is its current execution
context, which is either the enclosing function or, for variables
declared outside any function, global.
Assigning a value to an undeclared variable implicitly creates it as a
global variable (it becomes a property of the global object) when the
assignment is executed.

How does 'this' works in javascript? [duplicate]

This question already has answers here:
In Javascript, why is the "this" operator inconsistent?
(8 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 9 years ago.
hi i am a little confusion on how exactly this works in javascript.Based on this example:
var myFunction = function(){
function testMe(){
console.log(this) --------> DOMwindow
}
console.log(this) ---------> myFunction
}
var myvariable = new myFunction();
What is happening here?
The value this references depends on circumstances. Any unscoped (i.e. not in an object) function call will have this = window (DOMWindow, if you prefer). Anything that is part of a prototype, or has been changed using apply or bind, will have this as that object ("itself", if you prefer).
So, to illustrate. When you are instantiating using the new keyword, your function automatically inherits this as itself. When you call an IETF within it, this within this IETF will point to the global scope.
If you would like to avoid this, instead of calling testMe literally, you can always do this:
var myFunction = function() {
var testMe = function() {
console.log(this);
}
testMe.bind(this);
}
Which will, in turn, have this within testMe use the object as it should.

why without var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
seems stupid question but just curious.
num = "hello";
alert(num);
why is this possible I didnt initialize the num variable here.
num = "hello";
instead of
var num = "hello";
var means "Scope this variable to this function" not "Make it possible to use this variable".
If you leave var off then it will use the variable in the next scope up from the function. If that scope doesn't have the var yourVar then it will keep going up the scope chain until it becomes a global and dangles off the window object (assuming a browser or another JS environment in which the default object is window).
(This changes in strict mode, which you are presumably not using.)
Without the var keyword the variable is created at the global scope (in browsers under window).
If you add the var you just assign the variable to the current scope, which in most cases will be a function scope.
In general it will be better to use a function scope in order to not pollute the global scope and prevent conflicts between multiple variables of the same name!

Categories