javascript - Javascript 类返回未定义
问题描述
使用此代码时,该函数返回未定义而不是对象。
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";
对于其他运行良好的类,我有几乎相同的代码,所以我不知道为什么它不能正常运行
重复: 问题被标记为重复 [如何从异步调用返回响应?. 但是,我不想返回调用结果,我想返回一个包含用户名、密码、refresh_token 的对象......以及一个可以运行的方法。删除异步部分时,我遇到了完全相同的问题:
function Oauth_User_Profile() {
this.username = "=";
this.password = "=";
this.refresh_token = "=";
this.access_token = "=";
}
这仍然给出错误:Uncaught TypeError: Cannot set property 'username' of undefined at testm.html:67
解决方案
您缺少new
关键字:
var oauth_user_profile = new Oauth_User_Profile();
推荐阅读
- cakephp - CakePHP 3.x - 更改特定控制器的侧边栏
- microsoft-graph-api - Microsoft Graph API - 503 错误服务不可用
- azure-devops - 在 AzureDevOpps (VSTS) 内的 Cosmos Db (SQL API) 上创建数据库和集合
- node.js - 是否有任何可以处理重复 (RRULE) 事件的节点阅读器?
- c++ - 对 OpenCV 图像表示感到困惑
- c++ - 关于构造函数调用顺序和虚拟基类的混淆
- java - 使用带有杰克逊的过滤器将树结构序列化为 JSON
- angular - 调用服务后如何调用不同的 Ionic toast?
- java - 如何在另一个正在运行的类中调用函数?
- python - 不同的值会触发 Jupyter Notebook 内 Pandas 数据框中的 SettingWithCopyWarning