簡體   English   中英

ES6中的JavaScript范圍已轉換

[英]JavaScript Scope in ES6 transpiled

當我在一個項目中定義一個類時,我偶然在構造函數中創建了一個自變量。 當我將某些代碼從$ http.get回調移到函數中時遇到了一個問題。 自變量不再是同一范圍。 在我看來,構造函數的作用域與類的作用域相同,但事實並非如此。 這僅僅是轉堆的副作用還是ES6的工作方式?

一些代碼為清晰起見

(function () {
  class ServerManagementController {
    constructor($http, $scope, socket, Auth) {
      var self = this;
      this.$http = $http;
      this.$scope = $scope;
      ...
      $http.get('/api/servers').then(response => {
         //...code using self var - it became to long so I moved it out
         // into a function which broke the code and was fixed by moving
         // the var self outside of the constructor
         ...

附帶一提,您會推薦任何有關ES6的書籍?

var將變量綁定到函數的作用域,因此您的var self被綁定到函數的constructorclass只是將多個函數組合到一個類中的包裝器 ,但自身並未定義變量的作用域。

因此,您不能在constructor函數之外訪問self

class ServerManagementController {
  constructor($http, $scope, socket, Auth) {
    var self = this;
  }

  anotherFunction() {
  }
}

是因為如果你這樣寫的相同

function ServerManagementController($http, $scope, socket, Auth) {
  var self = this;
}

ServerManagementController.prototype.anotherFunction = function() {
}

在這兩種情況下, self都不能在anotherFunction

暫無
暫無

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

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