[英]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
被绑定到函数的constructor
, class
只是将多个函数组合到一个类中的包装器 ,但自身并未定义变量的作用域。
因此,您不能在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.