標籤:
this是javascript的一個關鍵字,隨著函數使用場合不同,this的值會發生變化。但是總有一個原則,那就是this指的是調用函數的那個對象。
1.全域代碼中的this
alert(this);//window
this指向全域對象。
2.作為單純的函數調用
function fooCoder(x) {
this.x = x;
}
fooCoder(2);
alert(x);// 全域變數x值為2
this指向全域對象,即window。在strict 模式中,則是undefined。
3.作為對象的方法調用
var name = "clever coder";
var person = {
name : "foocoder",
hello : function(sth){
console.log(this.name + " says " + sth);
}
}
person.hello("hello world");//foocoder says hello world
this指向person對象,即當前對象。
4.作為建構函式
new FooCoder();
this指向新建立的對象。
5.內建函式
var name = "clever coder";
var person = {
name : "foocoder",
hello : function(sth){
var sayhello = function(sth) {
console.log(this.name + " says " + sth);
};
sayhello(sth);
}
}
person.hello("hello world");//clever coder says hello world
在內建函式中,this沒有按預想的綁定到外層函數對象上,而是綁定到了全域對象。
6.使用call和apply設定this
person.hello.call(person, "world");//apply和call類似,只是後面的參數是通過一個數組傳入,而不是分開傳入
兩者都是將某個函數綁定到某個具體對象上使用,自然此時的this會被顯式的設定為第一個參數。
JS中this關鍵字