【问题标题】:Javascript Class returns undefinedJavascript 类返回未定义
【发布时间】:2018-11-12 08:34:37
【问题描述】:

使用此代码时,函数返回未定义而不是对象。

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";

其他类的代码几乎相同,但运行良好,所以我不知道为什么运行不正常

重复: 问题被标记为 [How do I return the response from an asynchronous call? 的重复项。但是,我不想返回调用结果,我想返回一个包含用户名、密码、refresh_token 的对象......以及一个可以运行的方法。删除异步部分时我遇到了完全相同的问题:

function Oauth_User_Profile() {
 this.username = "=";
 this.password = "=";
 this.refresh_token = "=";
 this.access_token = "=";
}

这仍然给出错误:Uncaught TypeError: Cannot set property 'username' of undefined 在 testm.html:67

【问题讨论】:

  • 你忘了用new调用构造函数
  • 为了更好的标准,在 JavaScript 中,我们使用 UpperCamelCase 表示类:Oauth_User_Profile => OauthUserProfile 和 lowerCamelCase 表示变量和函数:oauth_user_profile => oauthUserProfile

标签: javascript class oop


【解决方案1】:

您缺少new 关键字:

var oauth_user_profile = new Oauth_User_Profile();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多