this指向
今天就和大家來探討一下在js面向對象中的這個this的指向問題,
一般來講在函數中this的指向是當前函數的擁有者,也就是說當前誰這個函數,那么這個this就指向誰.
例:這里有一按鈕 btn
<input type ="button" id ="btn">
document.getElementById('btn').onclick = function(){
? ? ? ?alert(this)//input
}
此時this是指向按鈕 btn
第一種情況:
在面向對象中用了定時器
這里有一個對象;
function fn(){
? ? this.a= 1;//fn中的一個屬性
}
fn.prototype.show = function(){
? ?alert(this.a)//fn原型鏈上的一個方法
}
var obj = new fn();//實例化的時候
obj.show();//執行以下show()方法,彈出值為1
現在我們給這個對象加一個定時器看會怎么樣
function fn(){
this.a= 1;//fn中的一個屬性
? ? setInterval(this.show,1000)//定時器
}
fn.prototype.show = function(){
? ? alert(this.a)//fn原型鏈上的一個方法 彈出a的值
}
var obj = new fn();//實例化
這個時候函數在執行的時候 彈出值為undefined
為什么那?
現在我們來看一下這個this 是指向誰的
function fn(){
? ? ?this.a= 1;//fn中的一個屬性
? ? ? setInterval(this.show,1000)//定時器 彈出值是window
}
fn.prototype.show = function(){
? ? ? alert(this)
}
var obj = new fn();//實例化
原因就是定時器調用的函數都是指向`window`,所以我們這里彈出的都是`undefined` 因為window上沒有`show()`這個方法;
現在原因找到了怎么解決那,其實很簡單;
我們不要改變他的所屬關系就好,就像這樣:
function fn(){
? ? var _this = this //將我們原來的this賦給_this
? ? this.a= 1;//fn中的一個屬性
? ?//將原來的方法包一下目的就是不改變他們的所屬關系
? setInterval(function(){
? ? ? ?_this.show();
? ?},1000)//定時器
}
fn.prototype.show = function(){
? ? alert(this.a)//fn原型鏈上的一個方法? 彈出的就是:1
? ? //因為上面我們已經將this賦給_this了,所以此時this的指向就不在是window了,而是指向了obj
}
var obj = new fn();//實例化
好~~第一種情況我們已經接解決了,下面我們來看第二種情況,,,
第二種情況:
面向對象添加了事件的,
例:這里有一個按鈕
<input id="btn" type="button" value="按鈕"/>
function fn(){
? ? ? this.a = 1;
? ? ? document.getElmentById('btn').onclick = this.show;
? ?//彈出值為undefined 此時的this指向是input,而input是沒有 ? ?show()方法,所以undefined
}
fn.prototype.show = function(){
? ? alert(this.a)
}
new fn()
怎么解決那?
方法和含有定時器的一樣都是在原來的方法外面在套一層 并未把this重新附一下值;
function fn(){
? ?var _this = this
? ?this.a = 1;
? ?document.getElmentById('btn').onclick = function(){
? ? ? ?_this.show();//彈出值為1
? ?}
}
fn.prototype.show = function(){
? ?alert(this.a)
}
new fn()
其實這兩種情況的解決方式都用到了閉包,
將函數外面的this給存一下,然后通過閉包傳遞this
function fn(){
? ? var _this = this //存一下this
? ? this.a= 1;
? ? setInterval(function(){
? ? ? ? _this.show();//里面調用 ?
?},1000)
}
以上就是個人關于面向對象中的一些看法希望各位看官,多度指正 :>