本文實例講述了原生javascript中this幾種常見用法。分享給大家供大家參考,具體如下:
this的應用 “是” 代名詞
this必須出現在函數里面
//------------------默認綁定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;
//---------------------隱士綁定 多層調用鏈?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中只起到調用foo,所以thisl指的還是foo;
//---------------------隱士綁定 (隱士丟失) 多層調用鏈?function test (){ console.log(this.a);//1}var foo = { a:2, f:test}var a = 1;var fun = foo.f;fun();由于是賦值 調用的是fun(),foo.f 是取函數,但是this的對象是fun,是window對象,所以只能取得全局變量a
//1,this所在的函數是事件處理函數,那么this就是事件源;var btns = document.getElementsByTagName("button");獲取所有buttonfor(var i = 0; i < btns.length;i++){ btns[i].onclick = function(){ this代表當前事件源 console.log(this) }}// 2、this所在函數是構造函數,那么this就是new的對象,并且會生成__proto__屬性。function func(name,age){ this.name = name; this.age = age; // console.log(this)}let f = new func("z",20);// 3、this所在函數是類的方法,那么this就是調用方法時的對象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的轉移 轉移到windowvar btns = document.getElementsByTagName("button");//獲取所有buttonfor(let i = 0; i < btns.length;i++){ btns[i].onclick = function(){ console.log(this) // this代表點擊事件源 setTimeout(function(){ console.log(this); // this代表window對象 發生了轉移 },30) }}/*以上所說的所在函數,重點看關鍵字function。不會受箭頭函數的影響JavaScript中的一切的一切都屬于window對象。window對象可以省略。所有的全部變量,函數,類,都屬于window對象。this的轉移:發生在閉包里。*/感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.Vevb.com/code/HtmlJsRun測試上述代碼運行效果。
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《javascript面向對象入門教程》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
新聞熱點
疑難解答
圖片精選