gpt4 book ai didi

javascript - ES6 : what is equivalent of _this/self

转载 作者:行者123 更新时间:2023-11-28 00:08:51 24 4
gpt4 key购买 nike

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

let _$localStorage 来自 ( Injected dependencies not accessible in class methods for 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);
}
}

最佳答案

“this”的概念在 es6 中没有改变。

唯一不同的是当您使用 big arrow functions 时.

使用大箭头,“this”从调用函数传递到被调用函数(与将函数绑定(bind)到 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);
}

关于javascript - ES6 : what is equivalent of _this/self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31091394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com