0

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

Wonko the Sane
  • 10,623
  • 8
  • 67
  • 92
user2531284
  • 184
  • 1
  • 13
  • You forgot to call the constructor function with `new` – Quentin Nov 12 '18 at 08:37
  • Just for good standards, in JavaScript we use UpperCamelCase for classes: `Oauth_User_Profile` => `OauthUserProfile` and lowerCamelCase for variables and functions: `oauth_user_profile` => `oauthUserProfile` – Maor Refaeli Nov 12 '18 at 08:39

1 Answers1

3

You are missing the new keyword:

var oauth_user_profile = new Oauth_User_Profile();
Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33