简体   繁体   中英

behavior of let and const with javascript 'this' keyword

var num = 8;

const wantToKnowThis = function(val) {
  var num = 6;
  return this.num
}
console.log(wantToKnowThis(3));

if i run this code the answer will be 8 and that is correct but if run this code by just replacing let or const, it will give undefined!!

let num = 8;

const wantToKnowThis = function(val) {
  var num = 6;
  return this.num
}
console.log(wantToKnowThis(3));

is let and const behave diffrent with this keyword than var does please let me know??

If you use var in the global scope, then it will implicitly create a property of the same name on the window object.

The same is not true of const or let .


This doesn't really have anything to do with this other than at a couple of steps removed.

If you use this is a function with no context (ie which is not a method on an object and hasn't got a bound context via bind or => ), then this will be window (unless you use "use strict" and you should always use "use strict" as it prevents all kinds of gotchas)


If you want to access a variable outside of the function you are in then don't resort to global variable shenanigans. Simply don't give a local variable the same name in the first place .

 let num = 8; const wantToKnowThis = function(val) { let local_num = 6; return num; } console.log(wantToKnowThis(3)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM