JavaScript中的this機制,javascriptthis機制

來源:互聯網
上載者:User

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關鍵字的理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.