繁体   English   中英

ES6:等同于_this / self

[英]ES6: what is equivalent of _this / self

我试图通过转换现有的应用程序来了解ES6和Angular。 毫不奇怪,挑战就在this

let _$localStorage来自( 在AngularJS的类方法中无法访问注入的依赖项 ),但是那里已经有人提出这不是一个好方法。

我尝试实现的下一个问题也遇到了相同的问题,即如何在类中包含全局变量。

欢迎咨询

let _$localStorage;
//^^^^^^^^^^^^^^^^^
class MainSvc {
    constructor($http, $localStorage) {
        this.$http = $http;
        _$localStorage = $localStorage;

        this.data = {};
      //^^^^^^^^
        this.production = (location.host === "afbackend.herokuapp.com");
        this.baseUrl = location.protocol + '//' + location.host;

        console.log('MainSvc');
    }

    login(data, success, error) {
        this.$http.post(this.baseUrl + '/auth', data)
        .success(function(res)  {
            console.log("Login succeeded, token :", res.token);
            _$localStorage.token = res.token;
            this.data.user = getUserFromToken(res.token);
          //^^^^^^^^^^^^^^
            console.log(m);
            // success();
        })
        // .error(error);
    }
}

es6并未更改“ this”的概念。

对此唯一不同的是使用大箭头功能时

使用大箭头,“ this”从调用函数传递到被调用函数(与将函数绑定到此函数相同)。

因此,您仍然可以在类中自由使用它,但是请记住,当您使用不是大箭头的常规匿名函数时,如果要访问它,则仍然需要传递“ this”。

因此,要更正代码,您应该编写。

login(data, success, error) {
     var self = this;
        this.$http.post(this.baseUrl + '/auth', data)
        .success(function(res)  {
            console.log("Login succeeded, token :", res.token);
            _$localStorage.token = res.token;
            self.data.user = getUserFromToken(res.token);
          //^^^^^^^^^^^^^^
            console.log(m);
            // success();
        })
        // .error(error);
    }

也可以使用大箭头将其表示为:

    login(data, success, error) {
        this.$http.post(this.baseUrl + '/auth', data)
        .success((res) => { //Big arrow
            console.log("Login succeeded, token :", res.token);
            _$localStorage.token = res.token;
            this.data.user = getUserFromToken(res.token);
          //^^^^^^^^^^^^^^
            console.log(m);
            // success();
        })
        // .error(error);
    }

暂无
暂无

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

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