在处理一个项目时,我在iife中定义了一个类,但我意外地在构造函数中创建了一个self 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的书是什么?
发布于 2016-01-09 03:28:34
var
将变量绑定到函数的作用域,以便将var self
绑定到函数constructor
,class
只是将多个函数组合在一起的包装器,但没有为变量定义作用域。
因此,您不能在self
函数之外访问constructor
。
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
中都不可用。
https://stackoverflow.com/questions/34692796
复制