我刚写了一个这样的模块:
(function(){
'use strict';
angular.module('myApp.dashboard').controller('mainControl',mainControl);
mainControl.$inject = ['whichToShow','authService'];
function mainControl(whichToShow,authService){
var self=this;
this.values=whichToShow.getVar();
this.logOut=function(){
whichToShow.setVar(false);
authService.logOutUser();
};
this.removeEvent=function(eventId){
authService.removeEvent(eventId);
}
authService.setOnAuth(authDataCallback);
// Callback to set user's events.
function authDataCallback(authData) {
if (authData) {
console.log("User is logged in with " + authData.email);
self.eventList={};
whichToShow.setVar(true);
} else {
console.log("User is logged out");
}
}
}
})();
在此模块中self.eventList={};
行,首先我只使用this.eventList={}
,控制台始终告诉我TypeError: Cannot set property 'eventList' of undefined
。
直到我将self
设置为this
,并在authDataCallback函数中使用self
。我终于弄清楚如何解决它,但不知道为什么会这样?你能告诉我吗?
答案 0 :(得分:1)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
JS中的this
关键字是特定于上下文的。你的回调有它自己的执行上下文,所以this
指的是那个上下文而不是在周围的上下文中查找。
除了将其赋值给变量并对变量进行处理外,您可以使用.bind(this)
在函数的上下文中使用它,或者开始使用ES6胖箭头函数。