欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript嚴(yán)格模式下關(guān)于this的幾種指向詳解

 更新時(shí)間:2017年07月12日 11:50:51   作者:hgy  
除了正常運(yùn)行模式,ECMAscript 5添加了第二種運(yùn)行模式:"嚴(yán)格模式"(strict mode)。下面這篇文章主要給大家介紹了在JavaScript嚴(yán)格模式下關(guān)于this的幾種指向的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。

前言

相信不少人在學(xué)習(xí)或者使用Javascript的時(shí)候,都曾經(jīng)被 JavaScript 中的 this 弄暈了,那么本文就來整理總結(jié)一下在嚴(yán)格模式下 this 的幾種指向。

一、全局作用域中的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);
 this.a = 9804;
 console.log('this.a === window.a===',window.a);


二、全局作用域中函數(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();


三、 對(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());


四、構(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());


五、事件處理函數(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;
 }
 
 //這段代碼的作用是使被單擊的元素背景色變?yōu)樗{(lán)色

六、內(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 -->

后語

參考資料

MDN https://developer.mozilla.org...

延伸資料

JavaScript 嚴(yán)格模式詳解 http://www.dbjr.com.cn/article/74890.htm

菜鳥學(xué)堂 > JavaScript 嚴(yán)格模式 http://edu.jb51.net/js/js-strict.html

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論