JS中this關鍵字

來源:互聯網
上載者:User

標籤:

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關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.