web前端|js教程
JavaScript,this,js
web前端-js教程
除了正常运行模式,ECMAscript 5添加了第二种运行模式:”严格模式”(strict mode)。下面这篇文章主要给大家介绍了在JavaScript严格模式下关于this的几种指向的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。
最新能用代挂app源码,win7能安装vscode吗,ubuntu tty密码,最大文件数 tomcat,爬虫破解rsa,php 对象传值,关键词seo刻羽云lzw
前言
投票源码购买,dp没有输出 ubuntu,爬虫遇到443错误,php定义hash,seo走捷径lzw
相信不少人在学习或者使用Javascript的时候,都曾经被 JavaScript 中的 this 弄晕了,那么本文就来整理总结一下在严格模式下 this 的几种指向。
万人牛牛源码,用vscode做四个盒子,宏碁安装ubuntu,tomcat怎么改类型,爬虫新技术,php api调试工具,惠东推广抖音seo优化方案lzw
A、全局作用域中的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( his.a === window.a===,window.a);
B、全局作用域中函数中的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();
C、 对象的函数(方法)中的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());
D、构造函数的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());
E、事件处理函数中的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; } //这段代码的作用是使被单击的元素背景色变为蓝色
F、内联事件处理函数中的this
在严格模式下,在内联事件处理函数中,有以下两种情况: