簡體   English   中英

有人可以參考'this'關鍵字解釋此js代碼的工作方式嗎?

[英]Can someone explain working of this js code with reference to 'this' keyword?

JS代碼是:

this.sound1 ="global";

function cat(){
    this.sound = 'meawo!!!!';
    this.sound1 = 'meawooooo!!!!';

    meawo1 = function(){
        console.log(this.sound1);
        console.log(this);
    };

    function meawo2(){
        console.log(this.sound1);
        console.log(this);
    };

    this.meawo = function(){
        console.log(this.sound);
        console.log(this);
        meawo1();
        meawo2();
    };

};

var c = new cat();
c.meawo();

輸出為: 在此處輸入圖片說明

問:為什么this里面meawo1 (函數表達式) meawo2 (函數表達式聲明)指的是“全球性”,而不是反對c 這是為什么?

一定要記住一個簡單的提示,同時想知道哪個對象不this參考。

obj.method();

在上文中, method的調用上obj ,因此thismethod將它叫什么上,即obj = this

在你的情況下,雖然meowo叫上cmeowo1meowo2不是對象想要它來指代。

沒有明確的作用域的函數將被默認為全局上下文,盡管該函數本身不是全局的,並且由於閉包而可以利用其父上下文中的所有變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM