Javascript类返回未定义 [英] Javascript Class returns undefined
问题描述
使用此代码时,该函数返回未定义而不是对象。
When using this Code the function returns undefined instead of an object.
function Oauth_User_Profile() {
this.username = "=";
this.password = "=";
this.refresh_token = "=";
this.access_token = "=";
this.request = function(url, formData, method, then) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200)
{
var j = JSON.parse(this.responseText);
then(j);
}
}
xhttp.open(method, url);
xhttp.send(JSON.stringify(formData));
}
}
var oauth_user_profile = Oauth_User_Profile();
oauth_user_profile.username = "sample";
其他班级的代码差不多,但效果很好,所以我没有知道为什么它不能正常运行
I've got nearly the same Code for other classes which is working fine, so I don't know why this isn't running properly
重复:
问题被标记为[如何从异步调用返回响应?。但是,我不想返回调用结果,我想返回一个包含用户名,密码,refresh_token ...和可以运行的方法的对象。删除异步部分时,我遇到了完全相同的问题:
Duplicate: Question was marked as a duplicate for [How do I return the response from an asynchronous call?. However, I don't want to return the result of the call, I want to return an object which contains username, password, refresh_token... AND a method which can be run. I run into the exact same problem when removing the async-part:
function Oauth_User_Profile() {
this.username = "=";
this.password = "=";
this.refresh_token = "=";
this.access_token = "=";
}
这仍然会产生错误:未捕获的TypeError:无法设置属性'未定义
的用户名,位于testm.html:67
推荐答案
您丢失了 new
关键字:
var oauth_user_profile = new Oauth_User_Profile();
这篇关于Javascript类返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!