0

I declare class user, and then added an object of the class

function user(uid, pwd){
    this.uid = uid
    this.pwd = pwd
    function displayAll(){
        document.write(uid)
        document.write(pwd)
    }
}

var Aaron = new user("Aaron", "123")

document.write(Aaron.uid)

I want to roll through the properties printing them out one by one, I tried this

Aaron.displayAll()

which evaluates to nothing, am I missing something? Any help would be amazing :)

2
  • You need to return this at the end of the function Commented Apr 15, 2019 at 6:48
  • The function is declared withing the user function, but never binded to it, hence it's not exposed and can't be accessed, resulting in a function available only inside the user function. Commented Apr 15, 2019 at 6:54

3 Answers 3

7

This is what prototype chain is for.

function User(uid, pwd) {
  this.uid = uid
  this.pwd = pwd
}

User.prototype.displayAll = function() {
  document.write(this.uid)
  document.write(this.pwd)
}


var aaron = new User("Aaron", "123");


aaron.displayAll();

Sign up to request clarification or add additional context in comments.

Comments

1

Another way is to use Class syntax.

class User {
  constructor(uid, pwd) {
    this.uid = uid;
    this.pwd = pwd;
  }

displayAll(){
    document.write(this.uid);
    document.write(this.pwd);
  }
}

var Aaron = new User("Aaron", "123");
Aaron.displayAll();

Comments

0

You can change from function displayAll() to this.displayAll = function displayAll()

function user(uid, pwd)
    {
        this.uid = uid
        this.pwd = pwd
        this.displayAll = function displayAll()
        {
            document.write(uid)
            document.write(pwd)
        }
    }

    var Aaron = new user("Aaron", "123")

    document.write(Aaron.uid)
    Aaron.displayAll();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.