本文實例講述了javascript中this的用法。分享給大家供大家參考,具體如下:
實踐一:this在點擊等事件中的指向
html結(jié)構(gòu):
<button id='btn'>click me</button>
javascript結(jié)構(gòu):
var btn = document.getElementById('btn');btn.onclick = function(event) { console.log(this.innerHTML); // click me // 還有另一種做法如下,用事件對象 var evt = event || window.event; var target = evt.target || evt.srcElement; console.log(target.innerHTML); // click me}
實踐二:this在對象字面量json中的指向,指向自身對象
var p = { "name":"Tom", "say":function(){ console.log(this.name + ' say something!'); }}p.say(); // Tom say something!
實踐三:this在全局作用域中的使用
var a = 1;console.log(this); // windowconsole.log(this.a); // 1function test(){ console.log(this); // window this.haha = 'i am haha';};test(); // 函數(shù)一執(zhí)行,haha 作用域變成全局的console.log(haha); // i am haha
實踐四:this在定時器中的指向,定時器是window對象的一個方法,定時器中的this指向window對象,setTimeout()
和 setInterval()
是一樣的
var div = document.getElementById('div');div.onclick = function() { var that = this; // 用that 來存儲當前的div這個dom元素 setTimeout(function(){ console.log(this + ' i am this'); // [object Window] i am this console.log(that + ' i am that'); // [object HTMLDivElement] i am that }, 100);}
實踐五:this在對象中的指向,指向當前實例對象
function Person(){ this.name = 'jack';};Person.prototype = { buy:function() { console.log(this.name + ' go buy!'); }}var p = new Person();console.log(p.name); // jack;p.buy(); // jack go buy!
實踐六:this在閉包中的應(yīng)用1
var age = 20; var person = { "age" : 10, "getAgeFunc" : function(){ return function(){ return this.age; // this 指向 window }; } };console.log(person.getAgeFunc()()); // 20/* 分析這段代碼:person調(diào)用getAgeFunc() 在內(nèi)存中返回一個函數(shù),這個函數(shù)是全局的,然后加個() 執(zhí)行。那么,返回20*/
實踐七:this在閉包中的應(yīng)用2
var age = 20;var person = { "age" : 10, "getAgeFunc" : function(){ var that = this; return function(){ return that.age; // that 指向 person }; }};console.log(person.getAgeFunc()()); // 10/* 分析這段代碼:person調(diào)用getAgeFunc() 用that代替當前對象,當執(zhí)行返回的閉包函數(shù)時,age是person對象的一個屬性那么,返回10*/
實踐八:用call和apply改變this的指向 ,以后會詳細分析 call和apply以及閉包的概念
var person = { "name":"Tom", "say":function(x,y) { console.log(this.name + ' say ' + x + ' ' + y); }}var student = { "name":"Lucy"}person.say.call(student,'hello','world'); // Lucy say hello worldperson.say.apply(student,['hello','javascript']); // Lucy say hello javascript
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.VeVB.COm/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程序設(shè)計有所幫助。
新聞熱點
疑難解答