首页 > 解决方案 > 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

标签: javascriptclassoop

解决方案


您缺少new关键字:

var oauth_user_profile = new Oauth_User_Profile();

推荐阅读