網站搜尋

javascript - 處理 "this" 以存取類別欄位/方法


我對在 TypeScript 中使用 this 有點困惑,透過看這段程式碼

class GoogleMapsClass {
    public map;

    constructor(selector) {
        var _this = this;
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
                _this.map = this.responseText;
            }
        };
        xhttp.open("GET", "/test.php", false);
        xhttp.send();
    }
}

你可以看到我正在使用一個上下文切換技巧 var _this=this;

我不知道這是否是使用 TypeScript 處理類別欄位的正確方式,我也擔心使用這個技巧會讓記憶體重複分配,所以對性能和整體程式碼品質都不好(我知道 JavaScript 不是為某些重度運算而設計,但即使如此,物件的重複分配仍然是優化程式碼時最基本的錯誤)。

處理上下文切換的最正確方式是什麼?

答案#1

你的程式碼中沒有重複的物件。_this 只是 this 的一個參考。事實上,你可以使用箭頭函數或綁定你的函數來避免使用 _this。

綁定 :

class GoogleMapsClass {
    public map;

    constructor(selector) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4) {
                this.map = xhttp.responseText;
            }
        }.bind(this);
        xhttp.open("GET", "/test.php", false);
        xhttp.send();
    }
}

箭頭函式:

class GoogleMapsClass {
        public map;

        constructor(selector) {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = () => {
                if (xhttp.readyState == 4) {
                    this.map = xhttp.responseText;
                }
            }
            xhttp.open("GET", "/test.php", false);
            xhttp.send();
        }
    }

答案#2

我在你的程式碼中沒有看到任何地方你正在複製物件。

$(document).ready(function(){
  
  var first = {};
  var second = first;
  second.value = "whatever";

  $('#test1').text(first.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1"></div>

在上面的例子中,第一個和第二個指向同一個物件,物件沒有重複。我在第二個上設定了一個值,並且可以從第一個讀取它,因為它們字面上就是同一個物件。

處理上下文切換的最正確方式是什麼?

許多人會執行以下其中一行程式碼:

var _this = this;
var $this = this;
var self = this;

它們都可以運作,並且這樣做沒有任何實際的效能或記憶體問題。