function foo(){ return this; }
函數(shù)調(diào)用者是誰,就指向誰;直接調(diào)用指向window;
2.事件中:html事件中,指向window;dom0事件中,指向事件的觸發(fā)者(綁定元素的節(jié)點(diǎn));dom2事件中,非IE中指向綁定的元素節(jié)點(diǎn);IE中直接指向window;
3.閉包中:this指向window;
4.對象中:this指向當(dāng)前對象;如果有多級對象包裹,指代上一級對象;
( 1).
var foo = { a:18, num:{ a:10, num:function(){ console.log(this.a);//10 } } } foo.num.num();
(2).
var foo = { a:18, num:{ num:function(){ console.log(this.a);//undefined } } } foo.num.num();
5.call函數(shù)和apply函數(shù)能改變this的指向,bind函數(shù)也能改變函數(shù)指向;
6.構(gòu)造函數(shù)模塊:
總結(jié):構(gòu)造函數(shù)中,返回值是基本數(shù)據(jù)類型,那么this指向構(gòu)造函數(shù)的實(shí)例;返回值是對象則this指向該對象;
function Foo(){ this.user = 'my'; return {}; } var na = new Foo(); console.log(na.user);//返回值undefined; function Foo(){ this.user = 'my'; return 1; } var na = new Foo(); console.log(na.user);//返回值my
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com