• js 严格模式


    js严格模式下的this指向

    (全局作用域下的函数this指向由window变为undefined;定时器函数的this还是指向window)

    1、严格模式下全局作用域下的函数this指向undefined

    (function () {
      console.log(this);// 指向window
    }())
    
      (function () {
        "use strict"
        console.log(this);// 指向undefined
      }())
    

    2、非严格模式下的构造函数不加new当普通函数调用时,this指向window;

    而严格模式下,这样使用this会报错(因为this指向undefined);如果是使用new实例化的构造函数,this还是指向对象实例

    非严格模式
        function x() {
          this.name = 'name'
          console.log(this)// 指向window
        }
        x()
    
    严格模式
        function x() {
          "use strict"
          this.name = 'name' // undefined.name='name',所以报错
          console.log(this)// 指向undefined
        }
        x()
    

    3、严格模式下定时器函数的this依然指向window;

        "use strict"
        // 箭头函数的this指向上一层,这里是window
        setTimeout(() => {
          console.log(this); // 指向window
        }, 1000)
    
        // 定时器函数的this指向的是window
        setTimeout(function () {
          console.log(this); // 指向window
        }, 1000)
    
  • 相关阅读:
    用指针方法排序数组
    struct和typedef struct
    结构体类型定义的一般式
    HDOJ1020 Encoding
    malloc函数详解
    新手入门 acm 输入输出练习
    【算法入门】广度/宽度优先搜索(BFS)
    C++栈和队列
    hdu畅通工程
    codevs 2639 约会计划
  • 原文地址:https://www.cnblogs.com/xjt31/p/13734706.html
Copyright © 2020-2023  润新知