前言
相信不少人在学习或者使用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<elements.length ; i++){
elements[i].onclick = blue_it;
}
//这段代码的作用是使被单击的元素背景色变为蓝色
六、内联事件处理函数中的this
在严格模式下,在内联事件处理函数中,有以下两种情况:
<button onclick="alert((function(){'use strict'; return this})());">
内联事件处理1
</button>
<!-- 警告窗口中的字符为undefined -->
<button onclick="'use strict'; alert(this.tagName.toLowerCase());">
内联事件处理2
</button>
<!-- 警告窗口中的字符为button -->
后语
参考资料
MDN https://developer.mozilla.org...
延伸资料
JavaScript 严格模式详解 https://www.jb51.net/article/74890.htm
菜鸟学堂 > JavaScript 严格模式 http://edu.jb51.net/js/js-strict.html
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]



