简体   繁体   English

ES6中的JavaScript范围已转换

[英]JavaScript Scope in ES6 transpiled

While working on a project where I had defined a class inside of an iife I had accidentally created a self var inside of the constructor. 当我在一个项目中定义一个类时,我偶然在构造函数中创建了一个自变量。 I ran into a problem when I moved some code out of a $http.get callback and into a function. 当我将某些代码从$ http.get回调移到函数中时遇到了一个问题。 The self var was not the same scope anymore. 自变量不再是同一范围。 It would seem to me that the constructors scope would be the same as the classes scope but that is not the case. 在我看来,构造函数的作用域与类的作用域相同,但事实并非如此。 Is this just a side effect of transpiling or the way ES6 is meant to work? 这仅仅是转堆的副作用还是ES6的工作方式?

Some code for clarity 一些代码为清晰起见

(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
         ...

On a side note any books on ES6 you would recommend? 附带一提,您会推荐任何有关ES6的书籍?

var binds the variable to the scope of the function so your var self is bound to the function constructor , the class is just a wrapper grouping multiple functions together into a class, but does not define itself a scope for the variables. var将变量绑定到函数的作用域,因此您的var self被绑定到函数的constructorclass只是将多个函数组合到一个类中的包装器 ,但自身并未定义变量的作用域。

As of that you can't access self outside of the constructor function. 因此,您不能在constructor函数之外访问self

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

  anotherFunction() {
  }
}

Is the same as if you would write: 是因为如果你这样写的相同

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

ServerManagementController.prototype.anotherFunction = function() {
}

In both case self would be not available in anotherFunction . 在这两种情况下, self都不能在anotherFunction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM