JavaScript中的this機制,javascriptthis機制
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會被設定為傳入的第一個參數。
您可能感興趣的文章:
- javascript中onclick(this)用法介紹
- js中的this關鍵字詳解
- JS中的this變數的使用介紹
- javascript運行機制之this詳細介紹
- javascript中的self和this用法小結
- js this函數調用無需再次抓獲id,name或標籤名
- Javascript學習筆記之 函數篇(二) : this 的工作機制
- 深入理解Javascript中this的範圍
- JS函數this的用法執行個體分析
- 關於js裡的this關鍵字的理解