js严格模式下的this指向

一、全局作用域中的this

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

?
1
2
3
4
5
6
7
8
"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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"use strict" ;
 
console.log( "严格模式" );
console.log( '在全局作用域中函数中的this' );
function f1(){
console.log( this );
}
 
function f2(){
function f3(){
console.log( this );
}
f3();
}
f1();
f2();


三、 对象的函数(方法)中的this

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

?
1
2
3
4
5
6
7
8
9
10
"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指向构造函数创建的对象实例。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
"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指向触发事件的目标对象。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
"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

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

?
1
2
3
4
5
6
7
8
9
< button onclick = "alert((function(){'use strict'; return this})());" >
内联事件处理1
</ button >
<!-- 警告窗口中的字符为undefined -->
 
< button onclick = "'use strict'; alert(this.tagName.toLowerCase());" >
内联事件处理2
</ button >
<!-- 警告窗口中的字符为button -->

猜你喜欢

转载自blog.csdn.net/qq_36709020/article/details/80193225