JavaScript/变量提升

来自康健生活

引言

提升

for(var i=0;i<5; i++){
  console.info(i);
}
console.log(i);
0
1
2
3
4
5

避免提升

;(function(){
  for(var i=0;i<5; i++){
    console.info(i);
  }
})();
console.log(i);
0
1
2
3
4
Uncaught ReferenceError: i is not defined
    at <anonymous>:6:13

变量提升

字节的一道面试题,这道题没什么可讲的,考察的是作用域和变量提升

window.name = 'ByteDance';
function A () {
   this.name = 123;
}
A.prototype.getA = function(){
    console.log(this);
    return this.name + 1;
}
let a = new A();
let funcA = a.getA;
funcA();
ByteDance1