[英]Class variable is still undefined after being set in Javascript
I'm relatively new to Javascript and I can't seem to figure out why sessionToken isn't getting set. 我对Java还是比较陌生,似乎无法弄清sessionToken为何未设置。 When I console.log() it I get undefined even though I have just set it. 当我console.log()时,即使我刚刚进行设置,也无法定义。 What am I doing wrong? 我究竟做错了什么?
class Service extends Backend {
initialize(token) {
if (!_.isNull(token) && _.isUndefined(token.sessionToken)) {
throw new Error('Token missing');
}
this.sessionToken = _.isNull(token)
? null
: token.sessionToken.access_token;
console.log(this.sessionToken);
this.API_BASE_URL = CONFIG.backend.serviceLocal
? CONFIG.SERVICE.local.url
: CONFIG.SERVICE.remote.url;
this.CLIENT_ID = CONFIG.backend.serviceLocal
? CONFIG.SERVICE.local.client_id
: CONFIG.SERVICE.remote.client_id;
}
}
this.sessionToken = _.isNull(token)
? null
: token.sessionToken.access_token;
as said in the comment by Bulent Vural you're only checking if token exists and then assume that if it does also access_token is there. 如Bulent Vural在评论中所说,您仅检查令牌是否存在,然后假设它是否也存在access_token。 Seems that it is not the case and you get undefined. 似乎并非如此,并且您不确定。 I mocked your code here and if you don't pass access_token it will indeed fail with undefined. 我在这里嘲笑了您的代码,如果您不传递access_token,则它的确会因未定义而失败。 Maybe time to write some unit tests ? 也许是时候编写一些单元测试了? :) :)
Seems like you only care about the access_token
. 似乎您只在乎access_token
。 Why not throw if that's not defined? 如果未定义,为什么不抛出?
Try to write your function like this: 尝试这样编写函数:
initialize(token) { if (!(token && token.sessionToken && token.sessionToken.access_token)) { throw new Error('Access token missing'); } this.sessionToken = token.sessionToken.access_token; console.log(this.sessionToken); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.