user2531284
user2531284

Reputation: 184

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

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

This still gives the error: Uncaught TypeError: Cannot set property 'username' of undefined at testm.html:67

Upvotes: 0

Views: 1779

Answers (1)

Maor Refaeli
Maor Refaeli

Reputation: 2537

You are missing the new keyword:

var oauth_user_profile = new Oauth_User_Profile();

Upvotes: 3

Related Questions