Flynn
Flynn

Reputation: 25

Javascript OOP prototype functions return undefined

I'm trying to understand OOP in javascript and wrote those two files. My problem is the unexpected result of the prototype functions: undefined.

Did I miss something or did something wrong?

Module:

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

And this implements the 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();

And this is the output:

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

Upvotes: 0

Views: 556

Answers (2)

rfornal
rfornal

Reputation: 5122

The issue here is how your variables are declared and assigned:

Try ...

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

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

The variable assignment make it a locally accessible variable; using this allows the prototypes access to the variables. Using the this assignment, the variable is assigned to the object User in your case.

Upvotes: 3

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

Don't use private variable then:

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

Using var as in your example:

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

Upvotes: 0

Related Questions