JavaScript有自己的一套this機制,在不同情況下,this的指向也不盡相同。
全局范圍
console.log(this); //全局變量
全局范圍使用this指向的是全局變量,瀏覽器環境下就是window。
注:ECMAScript5的strict模式不存在全局變量,這里的this是undefined。
函數調用中
function foo() {  console.log(this);}foo(); //全局變量函數調用中的this也指向全局變量。
注:ECMAScript5的strict模式不存在全局變量,這里的this是undefined。
對象方法調用
var test = {  foo: function () {    console.log(this);  }}test.foo(); //test對象對象方法調用中,this指向調用者。
var test = {  foo: function () {    console.log(this);  }}var test2 = test.foo;test2(); //全局變量不過由于this的晚綁定特性,在上例的情況中this將指向全局變量,相當于直接調用函數。
這點非常重要,同樣的代碼段,只有在運行時才能確定this指向
構造函數
function Foo() {  console.log(this);}new Foo(); //新創建的對象console.log(foo); 在構造函數內部,this指向新創建的對象。
顯式設置this
function foo(a, b) {  console.log(this);}var bar = {};foo.apply(bar, [1, 2]); //barfoo.call(1, 2); //Number對象使用Function.prototype的call或者apply方法是,函數內部this會被設置為傳入的第一個參數。
新聞熱點
疑難解答