ES6中的JavaScript作用域已转换



在一个项目中,我在iife中定义了一个类,但我意外地在构造函数中创建了一个自var。当我将一些代码从$http.get回调移到一个函数中时,遇到了一个问题。self-var不再是同一个范围。在我看来,构造函数的作用域与类的作用域相同,但事实并非如此。这只是运输的副作用还是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() {
}

在这两种情况下,selfanotherFunction中将不可用。

最新更新