Javascript OOP原型函数返回undefined

时间:2015-01-13 18:24:35

标签: javascript oop scope

我正在尝试在javascript中理解OOP并编写这两个文件。我的问题是原型函数的意外结果:undefined。

我错过了什么或做错了吗?

模块:

/*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;

这实现了类:

/*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

2 个答案:

答案 0 :(得分:3)

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

尝试......

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

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

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

答案 1 :(得分:0)

然后不要使用私有变量:

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