严格模式是ES5增加的新概念。严格模式是一种不同的JavaScript解析和执行模型,对于不安全的活动抛出错误。使用严格模式需要在代码开头加上:”use strict”;也可以在函数体中单独使用,放在函数体开头:function fn(){“use strict”;}

总结:严格模式下执行函数时没有执行主体,因此this指向undefined,非严格模式下的执行主体默认是window,因此this指向window

1. 自执行函数下的this

严格模式

  • this为undefined

    1. "use strict";
    2. function fn(){
    3. console.log(this)
    4. }
    5. fn() // undefined

    非严格模式

  • this为window

    1. function fn(){
    2. console.log(this)
    3. }
    4. fn() // window

    注意:

  • 箭头函数在严格模式和非严格模式下的this一致

  • 严格模式或非严格模式下,使用call,apply,bind等结果一致

    1. "use strict";
    2. const fn = ()=>{
    3. console.log(this)
    4. }
    5. fn() // window
    6. let obj = {}
    7. fn.call(obj) //obj 严格模式与非严格模式一致

    2. 事件绑定函数中的this

    严格模式与非严格模式一致,非箭头函数指向当前操作的元素,箭头函数指向window

  • 非箭头函数

    1. // 严格模式
    2. "use strict";
    3. function fn(){
    4. console.log(this)
    5. }
    6. const btn = document.getElementById('btn')
    7. btn.addEventListener('click',fn)//<button id="btn">按钮</button>
    1. // 非严格模式
    2. const btn = document.getElementById('btn')
    3. btn.addEventListener('click', function (){
    4. console.log(this) // <button id="btn">按钮</button>
    5. })
  • 箭头函数

    1. // 严格模式
    2. "use strict";
    3. const btn = document.getElementById('btn')
    4. btn.addEventListener('click', ()=>{
    5. console.log(this) // window
    6. })
    1. // 非严格模式
    2. const btn = document.getElementById('btn')
    3. btn.addEventListener('click', ()=>{
    4. console.log(this) // window
    5. })

    3. 对象的方法

  • 通过对象调用方法,严格模式与非严格模式的this指向一致

  • 将方法赋值后直接调用,严格模式下是undefined,非严格模式是window

    1. "use strict";
    2. const obj = {
    3. fn:function(){
    4. console.log(this)
    5. }
    6. }
    7. obj.fn() // obj
    8. obj.fn.call(window) // window
    9. const fn2 = obj.fn
    10. fn2() // undefined,非严格模式下是window

    4. 构造函数

    严格模式

  • 通过实例调用this指向实例,通过构造函数调用,this指向构造函数

  • 先赋值后再调用,this指向undefined

    1. "use strict";
    2. function Demo(){ }
    3. Demo.prototype.callthis = function(){
    4. console.log(this)
    5. }
    6. Demo.fn = function(){
    7. console.log(this)
    8. }
    9. const d = new Demo()
    10. d.callthis() // d
    11. Demo.fn() // Demo
    12. let fn = d.callthis
    13. fn() // undefined 非严格模式下是window

    非严格模式

  • 先赋值后再调用,this指向window

    1. function Demo() { }
    2. Demo.prototype.callthis = function () {
    3. console.log(this)
    4. }
    5. Demo.fn = function () {
    6. console.log(this)
    7. }
    8. const d = new Demo()
    9. d.callthis() // d
    10. Demo.fn() // Demo
    11. let fn = d.callthis
    12. fn() // window

    5. 类中的方法默认开启了严格模式

  • 由于callthis方法实在类中定义的,该方法内部默认开启了严格模式,因此先赋值再调用时,其this指向了undefined

    1. // 非严格模式
    2. class Demo{
    3. callthis(){
    4. console.log(this)
    5. }
    6. static fn(){
    7. console.log(this)
    8. }
    9. }
    10. const d = new Demo()
    11. // d.callthis() // d
    12. // Demo.fn() // Demo
    13. let fn = d.callthis
    14. fn() // undefined