首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JavaScript变换在ES6中的作用域

JavaScript变换在ES6中的作用域
EN

Stack Overflow用户
提问于 2016-01-09 11:18:37
回答 1查看 58关注 0票数 0

在处理一个项目时,我在iife中定义了一个类,但我意外地在构造函数中创建了一个self var。当我将一些代码从$http.get回调中移到函数中时,遇到了一个问题。self var不再是相同的范围了。在我看来,构造函数作用域与类作用域是相同的,但事实并非如此。这仅仅是转移的副作用,还是ES6的工作方式?

一些清晰的代码

代码语言:javascript
运行
复制
(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的书是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-09 11:28:34

var将变量绑定到函数的作用域,以便将var self绑定到函数constructorclass只是将多个函数组合在一起的包装器,但没有为变量定义作用域。

因此,您不能在self函数之外访问constructor

代码语言:javascript
运行
复制
class ServerManagementController {
  constructor($http, $scope, socket, Auth) {
    var self = this;
  }

  anotherFunction() {
  }
}

是相同的,就好像您会写:

代码语言:javascript
运行
复制
function ServerManagementController($http, $scope, socket, Auth) {
  var self = this;
}

ServerManagementController.prototype.anotherFunction = function() {
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34692796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档