首页 > web前端 > js教程 > 正文

有关JavaScript严格模式下this的指向问题详解

巴扎黑
发布: 2018-05-29 13:43:41
原创
1543 人浏览过

除了正常运行模式,ECMAscript 5添加了第二种运行模式:"严格模式"(strict mode)。下面这篇文章主要给大家介绍了在JavaScript严格模式下关于this的几种指向的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

相信不少人在学习或者使用Javascript的时候,都曾经被 JavaScript 中的 this 弄晕了,那么本文就来整理总结一下在严格模式下 this 的几种指向。

一、全局作用域中的this

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

 "use strict";
 
 console.log("严格模式");
 console.log("在全局作用域中的this");
 console.log("this.document === document",this.document === document);
 console.log("this === window",this === window);
 this.a = 9804;
 console.log('this.a === window.a===',window.a);
登录后复制


二、全局作用域中函数中的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();
登录后复制


三、 对象的函数(方法)中的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());
登录后复制


四、构造函数的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());
登录后复制


五、事件处理函数中的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
登录后复制

六、内联事件处理函数中的this

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

 
 
 
 
 
登录后复制

以上是有关JavaScript严格模式下this的指向问题详解的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!