无法访问Javascript中的对象方法

时间:2019-04-15 06:46:14

标签: javascript methods

我声明了类用户,然后添加了该类的对象

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)

我想逐一浏览属性,我尝试过

Aaron.displayAll()

评估为零,我缺少什么吗? 任何帮助都将是惊人的:)

4 个答案:

答案 0 :(得分:6)

这就是原型链的用途。

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();

答案 1 :(得分:1)

另一种方法是使用Class语法。

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();

答案 2 :(得分:0)

您可以从function displayAll()更改为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();

答案 3 :(得分:-1)

您需要返回内部函数。

function user(uid, pwd)
    {
        this.uid = uid
        this.pwd = pwd
        function displayAll()
        {
            document.write(uid)
            document.write(pwd)
        }
        return displayAll();
    }
 // And Following statement will write properties. 
    var Aaron = new user("Aaron", "123");