1. 全局作用域中的this
在嚴(yán)格模式下,在全局作用域中,this指向window對(duì)象
"use strict";
console.log("嚴(yán)格模式");
console.log("在全局作用域中的this");
console.log("this.document === document",this.document === document);
console.log("this === window",this === window);
2. 全局作用域中函數(shù)中的this
在嚴(yán)格模式下,這種函數(shù)中的this等于undefined
"use strict";
console.log("嚴(yán)格模式");
console.log('在全局作用域中函數(shù)中的this');
function f1(){
console.log(this);
}
function f2(){
function f3(){
console.log(this);
}
f3();
}
f1();
f2();
3. 對(duì)象的函數(shù)(方法)中的this
在嚴(yán)格模式下,對(duì)象的函數(shù)中的this指向調(diào)用函數(shù)的對(duì)象實(shí)例
"use strict";
console.log("嚴(yán)格模式");
console.log("在對(duì)象的函數(shù)中的this");
var o = new Object();
o.a = 'o.a';
o.f5 = function(){
return this.a;
}
console.log(o.f5());
image.png
4. 構(gòu)造函數(shù)的this
在嚴(yán)格模式下惋嚎,構(gòu)造函數(shù)中的this指向構(gòu)造函數(shù)創(chuàng)建的對(duì)象實(shí)例。
"use strict";
console.log("嚴(yán)格模式");
console.log("構(gòu)造函數(shù)中的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. 事件處理函數(shù)中的this
在嚴(yán)格模式下站刑,在事件處理函數(shù)中另伍,this指向觸發(fā)事件的目標(biāo)對(duì)象。
"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. 內(nèi)聯(lián)事件處理函數(shù)中的this
在嚴(yán)格模式下,在內(nèi)聯(lián)事件處理函數(shù)中摆尝,有以下兩種情況:
<button onclick="alert((function(){'use strict'; return this})());">
內(nèi)聯(lián)事件處理1
</button>
<!-- 警告窗口中的字符為undefined -->
<button onclick="'use strict'; alert(this.tagName.toLowerCase());">
內(nèi)聯(lián)事件處理2
</button>
<!-- 警告窗口中的字符為button -->