簡體   English   中英

我對JavaScript中的關鍵字'this'感到困惑

[英]I am confused about the keyword 'this' in JavaScript

這是一個例子:

function one() {

    var a = 1;
    two();

    function two() {

        var b = 2;
        three();

        function three() {

            var c = 3;
            alert(a + b + c); // 6

        }
    }   
}

one()​; //calling the function

現在當我們調用函數one()時,結果為6

所以關於范圍鏈,所有變量都已解決,現在我有一個問題。

當所有變量通過范圍鏈解析時,為什么我們需要這個“ this ”關鍵字?

所以如果我們有以下功能:

function a() {
    var a = 'function a';

    function b() {
        var b = 'function b';
        alert (a); //will be function a, without keyword this 
        alert (this.a); // what will be the effect of this line
    }
}

“this”關鍵字總是讓我困惑!

有人請以簡單的方式詳細解釋。

他們關鍵字this是在JavaScript中的一個功能,通過以下方式解決-

  1. 在對象上或通過對象調用函數時,該對象是函數的調用上下文或“this”值。 例如 -

     var o = { f : function(){ //do something } } 

    如果我們使用對象'o'調用對象'o'的方法'f' -

     of()// in method f, 'this' refers to o inside the method o 
  2. 如果未通過對象調用函數,則當前窗口對象是調用上下文或函數的this值。 例如 -

     function f(){ //do something } //calling f f();// 'this' will refer to current window object 

在您的情況下,這指的是當前窗口對象, this.a是對您在全局范圍中定義的函數a的引用。

此外,可以在調用函數時提供函數的調用上下文或“this”值。 請檢查Function.prototype.call方法 - JavaScript | MDNFunction.prototype.apply方法 - JavaScript | MDN

this關鍵字指的是函數的范圍。 在上面的代碼中, this.a將打印undefined,因為沒有名為a的變量。 this關鍵字用於引用當前本地范圍而不是全局范圍。 因此,如果你在函數b中有一個名為a的變量,那么this.a將引用函數b中定義的變量而不是它之外的變量。 雖然在函數b之外引用它將引用全局范圍。

暫無
暫無

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

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