简体   繁体   中英

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

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?

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.

As of that you can't access self outside of the constructor function.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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