let和const的变量声明不在window对象上

78 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

问题引出:

下面打印出的为什么是 hello outPeople 而不是hello innnerPeople?

var people = "outPeople";
  function hello() {
    let people = "innnerPeople";
    console.log("hello", this.people);
  }
  hello(); // hello outPeople
  // 上面的是下面的语法糖
  hello.call(window); // hello outPeople

提问:是因为let和var的区别么?

那么将people的声明改为let的声明会发生什么呢?

let people = "outPeople";
  function hello() {
    let people = "innnerPeople";
    console.log("hello", this.people);
  }
  hello(); // hello undefined
  // 上面的是下面的语法糖
  hello.call(window); // hello undefined

打印的结果直接变为 hello undefined

推测:window上是不是没有people这个属性

  // var定义的变量
  var var_person_name = "var_kyrene";
  // let和const定义的变量
  let let_person_name = "let_kyrene";
  const CONST_PERSON_NAME = "const_kyrene";

  console.log(window.var_person_name); // var_kyrene
  console.log(window.let_person_name); // undefined
  console.log(window.CONST_PERSON_NAME); // undefined

由此可见,确实let和const声明的变量是不在window对象上的

一道面试题

  let age = 10;
  function fun() {
    console.log(this.age);
  }
  fun();
  let student = {
    height: 150,
    hello: function () {
      fun();
      arguments.age = 12;
      arguments[0]();
    },
  };
  student.hello(fun);

输出结果为:

undefined 
undefined 
12

面试题解析

首先

fun(),函数直接执行,等价于fun.call(window),this指向window,所以打印window.age,window上无age,故为undefined

其次

student.hello(fun),函数作为对象的方法被调用 在其执行过程中,fun()函数以及直接执行,等价于fun.call(window),故打印undefined

最后

arguments.age = 12;给arguments添加age属性,然后arguments调用自身的函数,所以this执行arguments,故打印12