Javascript OOP 原型函数 return 未定义

Javascript OOP prototype functions return undefined

我试图理解 javascript 中的 OOP 并编写了这两个文件。我的问题是原型函数的意外结果:未定义。

我是漏掉了什么还是做错了什么?

模块:

/*jslint node: true */

function User(tid, tname, ttype) {
    'use strict';
    this.id = tid;
    var name = tname,
        type = ttype;

    console.log("user: " + this.id + " created.");
}

User.prototype.getName = function () {
    'use strict';
    return this.name;
};

User.prototype.getType = function () {
    'use strict';
    return this.type;
};

module.exports = User;

这实现了 class:

/*jslint node: true */
var User = require('./User');

var userlist = [];

function init() {
    'use strict';
    var namelist = ['Boz', 'Nash', 'Joe', 'Angel'],
        i = 0,
        tUser;

    for (i = 0; i < namelist.length; i += 1) {
        tUser = new User(i + 1, namelist[i], 0);

        userlist.push(tUser);

    }
}

function print() {
    'use strict';
    var tString,
        i;

    for (i = 0; i < userlist.length; i += 1) {
        tString = "User Entry:" + i + " | ";
        tString += userlist[i].getName() + " | ";
        tString += userlist[i].getType() + " | ";
        tString += userlist[i].id;
        console.log(tString);
    }
}

init();
print();

这是输出:

user: 1 created.
user: 2 created.
user: 3 created.
user: 4 created.
User Entry:0 | undefined | undefined | 1
User Entry:1 | undefined | undefined | 2
User Entry:2 | undefined | undefined | 3
User Entry:3 | undefined | undefined | 4

这里的问题是如何声明和分配变量:

尝试...

function User(tid, tname, ttype) {
    'use strict';
    this.id = tid;
    this.name = tname;
    this.type = ttype;

    console.log("user: " + this.id + " created.");
}

变量赋值使其成为本地可访问变量;使用它允许原型访问变量。在您的例子中,使用 this 赋值,变量被分配给对象 User

那就不要使用私有变量:

this.id = tid;
this.name = tname,
this.type = ttype;

在您的示例中使用 var

this.id = tid;//available in other functions
var name = tname,
    type = ttype;//won't allow you to access in other functions