js 变量提升,this指向那些事

53 阅读1分钟

js中的变量提升

函数和全局变量都存在变量提升,也就是提升到最顶部执行

  • 即先使用完变量再声明变量
x = 5;
console.log(x);   // 5
var x;
  • 这就是先把变量声明var x 提升到最顶部,相当于先声明,再初始化x
var x; // 声明 x
x = 5; // 初始化
console.log(x);   // 5
  • 类似一些变体可以先拆解后在计算
console.log(x); 
var x = 8;

// 拆分一下

console.log(x); 
var x;
x = 8;

// 声明会悄悄提升 变成以下执行顺序
var x;
console.log(x);  // undefined
x = 8;
  • 函数作用域中也存在变量提升,和上述转换同理
function fn(){
    console.log(x);   // undefined
    var x = 5;
}

为了解决上述问题,ES6 引入了let const ,之前只有全局作用域和函数作用域,现在有块级作用域,letconst是不存在变量提升的

this 指向

  • jsthis表示当前对象的一个引用,单独使用this 表示全局对象(window)。
  • JavaScriptthis 不是固定不变的,它会随着执行环境的改变而改变。
  • 简单来说就是 this 指向只看调用的位置,不看声明的位置
console.log(this);  // window

var person = { 
    firstName: "John", 
    fullName : function() { 
        return this.firstName;  // person
    } 
};
person.fullName() // 谁在调用this就指向谁
  • call() 和 apply() 方法可以将 this 引用到任何对象。
var person = { 
    firstName: "John", 
    fullName : function() { 
        return this.firstName;  // person
    } 
};
var person2={
    firstName: "Amy"
}
person.fullName.call(person2)  // person2
  • 在函数中,在严格模式下,this 是未定义(undefined)
"use strict";
myFunction();
function myFunction() {
  return this; // undefined
}
  • 箭头函数例外,它没有自己的this指向,它的this指向上一级作用域的this
  • call()apply()无法改变箭头函数 this指向
var person = {
  firstName  : "John",
  myFunction : ()=>{
    return this; 
  }
};
person.myFunction() // window

// 无法改变

var person2={
    firstName: "Amy"
}
person.myFunction.call(person2)  // window