严格模式下this的几种指向

1. 全局作用域中的this

在严格模式下,在全局作用域中,this指向window对象

    "use strict";
    console.log("严格模式");
    console.log("在全局作用域中的this");
    console.log("this.document === document",this.document === document);
    console.log("this === window",this === window);

2. 全局作用域中函数中的this

在严格模式下,这种函数中的this等于undefined

    "use strict";
    
    console.log("严格模式");
    console.log('在全局作用域中函数中的this');
    function f1(){
      console.log(this);
    }
    
    function f2(){
      function f3(){
        console.log(this);
      }
      f3();
    }
    f1();
    f2();

3. 对象的函数(方法)中的this

在严格模式下,对象的函数中的this指向调用函数的对象实例

    "use strict";
    
    console.log("严格模式");
    console.log("在对象的函数中的this");
    var o = new Object();
    o.a = 'o.a';
    o.f5 = function(){
      return this.a;
    }
    console.log(o.f5());
image.png

4. 构造函数的this

在严格模式下,构造函数中的this指向构造函数创建的对象实例。

  "use strict";
    console.log("严格模式");
    console.log("构造函数中的this");
    function constru(){
      this.a = 'constru.a';
      this.f2 = function(){
        console.log(this.b);
        return this.a;
      }
    }
    var o2 = new constru();
    o2.b = 'o2.b';
    console.log(o2.f2());
image.png

5. 事件处理函数中的this

在严格模式下,在事件处理函数中,this指向触发事件的目标对象。

    "use strict";
    
    function blue_it(e){
      if(this === e.target){
        this.style.backgroundColor = "#00f";
      }
    }
    var elements = document.getElementsByTagName('*');
    for(var i=0 ; i<elements.length ; i++){
      elements[i].onclick = blue_it;
    }

6. 内联事件处理函数中的this

在严格模式下,在内联事件处理函数中,有以下两种情况:

 <button onclick="alert((function(){'use strict'; return this})());">
      内联事件处理1
    </button>
    <!-- 警告窗口中的字符为undefined -->
    
    <button onclick="'use strict'; alert(this.tagName.toLowerCase());">
      内联事件处理2
    </button>
    <!-- 警告窗口中的字符为button -->
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容