javascript
javascript中的this讲解
function test(){
alert(this);//test這個函數(shù)沒有所有者,因此此時this指向的是window
}
o.test = function(){
alert(this==o);//輸出true,o.test表示的是test這個函數(shù)的所有者是對象o,因此this應(yīng)當是指向o的
}
3)綁定函數(shù)時的this 1 如下代碼,test1和test2中this并不相同var test2 = o.test1;//test2這個函數(shù)并沒有所有者,在此,test2雖然調(diào)用了test1這個函數(shù),但是this仍然指向window,而不是指向test1的擁有者:對象o
test2();
o.test1 = function(){
alert(this===o);
}
這便是上面所說的,要將函數(shù)與函數(shù)名分開看待 4)綁定函數(shù)時的this 2 此時如果我們對3)中的代碼進行一些修改:function test () {
alert(this === o);
}
test();//this指向window
var o = {};
o.test2 = test;
o.test2();//此時test2的所有者為o,而test沒有所有者,this在此時指向的是o
alert(o.test2);
document.onclick=function(){
alert(this===document);//輸出為true,onclick事件的擁有者是document。因此,此處this指向document。我們可以將document.onclick理解為一個對象方法,如同例4中的o.test2一樣。
}
6)setTimeout等傳參形式的this指向 不要去看傳的參數(shù)中函數(shù)的所有者,看執(zhí)行函數(shù)的所有var obj = {};obj.x = 1;
obj.y = 2;
window.x = 100;
window.y = 200;
obj.add = function () {
alert(this.x + this.y);
}
setTimeout(obj.add,1000);//this指向window,輸出為300
setTimeout(function(){//this指向obj,輸出為3
obj.add();
},1000);
var oo = {};
oo.test3 = function(){
alert(this == oo);//返回false
}
var ooo = {};
oo.test3.call(ooo);//this指向的是()內(nèi)的第一個參數(shù),此處為ooo
window.x = 100;
var oo = {};
oo.test3 = function(y,z,k){//函數(shù)的參數(shù)與apply、call中第二個以及之后的參數(shù)相對應(yīng)
alert(this.x+y+z+k);
}
var arr=[2,3,4]
oo.test3.call(window,2,3,4);//this指向window,輸出為109
oo.test3.apply(window,[2,3,4]);//同上,使用apply進行元素羅列時需要使用中括號[]將所有參數(shù)包裹起來
oo.test3.apply(window,arr);//同上,使用apply對于一個數(shù)組的訪問很簡單,使用數(shù)組名稱即可
oo.test3.call(window,arr[0],arr[1],arr[2]);//同上
轉(zhuǎn)載自:http://blog.163.com/hongshaoguoguo@126/blog/static/18046981201251935720333/
總結(jié)
以上是生活随笔為你收集整理的javascript中的this讲解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何写一个数据库中间件以及需要准备的知识
- 下一篇: nodejs怎么与c语言通信费是什么,N