javascript中的this詳解,javascriptthis詳解

來源:互聯網
上載者:User

javascript中的this詳解,javascriptthis詳解

This對象在js中就一直是個坑貨,很難判斷它到底指向什麼,而我們由於來自C++或者python的self的經驗,又常常會犯這一類的錯誤。接下來就詳細地講一下this對象的歸屬。

rule1:全域環境的this

javascript的環境天生就由函數來決定,在js裡不能通過代碼塊隔開上下文,不被函數所包裹的環境就是全域環境,全域環境中的this就指向全域變數window,看下面一個例子

複製代碼 代碼如下:
var name='jjj';
console.log(this.name);
//會成功輸出jjj

rule2:作為方法調用時的this

顯然這種情況很好判斷,與python裡的self是一致的,this毫無疑問指向調用方法的對象

複製代碼 代碼如下:
var user={
    name:'kkk'
};
user.getName=function(){
    console.log(this.name);
};
user.getName();
//會輸出kkk

rule3:作為建構函式時的this

這時的this也不用我多說,顯然是指向新建立的對象,建構函式的運行其實並不建立對象,而僅僅是初始化,對象在運行之前就已經被建立
下面還是舉例說明

複製代碼 代碼如下:
function User(name){
    this.name=name;
}
var f1=new User('kkk');
var f2=User('kkk');
console.log(f1.name);//kkk
console.log(f2.name);//undefined沒有name屬性

rule4:間接調用中的this

所謂間接調用是指利用apply和call來調用函數,這時的this指向它們參數列表中的第一個參數。

複製代碼 代碼如下:
var setName=function(name){
    this.name=name;
};
var user={level:2};
user.apply(setName,'jjj');
console.log(user.name);//jjj

rule5:其他情況中的this

記住其他情況下this均不會被改變,這裡也是最容易犯錯的地方。

複製代碼 代碼如下:
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不應該指向person嗎?
我們應該記住被嵌套的函數中的this是不會指向嵌套它的函數,在這個例子裡面就是sayhello中的this不會指向hello對應的那個函數。如果我們把例子稍稍改一下變成

複製代碼 代碼如下:
hello:function(sth){
    console.log(this.name + " says " + sth);
}
//foocoder says hello world

大家應該已經看明白了,這個時候,sayhello並非在作為方法調用,所以this指向全域對象。。。
這時候問題來了,用node運行最初的例子會顯示undefined says hello world,不知道有沒有大神講解一下。

rule6:eval破壞所有規則

最後以一個例子結束

複製代碼 代碼如下:
var name = "clever coder";
var user={
    name:'kkk'
};
user.getName=function(){
    console.log(this.name);
};
var get=user.getName;
get();//clever coder

大家是否明白了?

聯繫我們

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