原生javascript中this幾種常見用法總結(jié)
本文實例講述了原生javascript中this幾種常見用法。分享給大家供大家參考,具體如下:
this的應用 “是” 代名詞
this必須出現(xiàn)在函數(shù)里面
//------------------默認綁定 function test (){ console.log(this.a);//1 } var a = 1; test();
this取得是window的對象a;此處默認window
//---------------------隱士綁定? function test (){ console.log(this.a);//2 } var foo = { a:2, f:test } var a = 1; foo.f();
此處this取得是foo對象的a;
//---------------------隱士綁定 多層調(diào)用鏈? function test (){ console.log(this.a);//3 } var foo = { a:3, f:test } var foo2 = { a:4, f:foo } var a = 1; foo2.f.f();
此處this取得是foo對象的a,foo2中只起到調(diào)用foo,所以thisl指的還是foo;
//---------------------隱士綁定 (隱士丟失) 多層調(diào)用鏈? function test (){ console.log(this.a);//1 } var foo = { a:2, f:test } var a = 1; var fun = foo.f; fun();
由于是賦值 調(diào)用的是fun(),foo.f 是取函數(shù),但是this的對象是fun,是window對象,所以只能取得全局變量a
//1,this所在的函數(shù)是事件處理函數(shù),那么this就是事件源; var btns = document.getElementsByTagName("button"); 獲取所有button for(var i = 0; i < btns.length;i++){ btns[i].onclick = function(){ this代表當前事件源 console.log(this) } }
// 2、this所在函數(shù)是構(gòu)造函數(shù),那么this就是new的對象,并且會生成__proto__屬性。 function func(name,age){ this.name = name; this.age = age; // console.log(this) } let f = new func("z",20);
// 3、this所在函數(shù)是類的方法,那么this就是調(diào)用方法時的對象 function Fnc(name,age){ this.name = name; this.age = age; } Fnc.prototype.eat = function(){ console.log(this); } let fn = new Fnc("a",12); fn.eat(); let fn2 = new Fnc("b",10); fn2.eat();
// 4、this的轉(zhuǎn)移 轉(zhuǎn)移到window var btns = document.getElementsByTagName("button"); //獲取所有button for(let i = 0; i < btns.length;i++){ btns[i].onclick = function(){ console.log(this) // this代表點擊事件源 setTimeout(function(){ console.log(this); // this代表window對象 發(fā)生了轉(zhuǎn)移 },30) } } /* 以上所說的所在函數(shù),重點看關(guān)鍵字function。不會受箭頭函數(shù)的影響 JavaScript中的一切的一切都屬于window對象。window對象可以省略。 所有的全部變量,函數(shù),類,都屬于window對象。 this的轉(zhuǎn)移:發(fā)生在閉包里。*/
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學運算用法總結(jié)》
希望本文所述對大家JavaScript程序設計有所幫助。
相關(guān)文章
window.location和document.location的區(qū)別分析
用戶不能改變document.location(因為這是當前顯示文檔的位置)。但是,可以改變window.location (用其它文檔取代當前文檔)window.location本身也是一個對象,而document.location不是對象2008-12-12談談JSON對象和字符串之間的相互轉(zhuǎn)換JSON.stringify(obj)和JSON.parse(string)
這篇文章主要介紹了談談JSON對象和字符串之間的相互轉(zhuǎn)換JSON.stringify(obj)和JSON.parse(string)以及JSON的parse()和stringfy()方法詳解,感興趣的朋友一起看看吧2015-10-10