Dan P.
Dan P.

Reputation: 1775

Prototype JavaScript -- function using constructor function

I have this code:

function user(name) {
    console.log(name);
}

user.prototype.test = function() {
    return 2 + 2;
};

console.log(user.prototype.test());

var dany = new user("dany");
var david = new user("david");

console.log(dany.prototype.test());

Console logs:

4
dany
david
Uncaught TypeError: Cannot call method 'test' of undefined

Shouldn't the test() function be assigned to all instances of the user() function (which is the object constructor) ?

If you happen to have good recommendations on what I should read to understand prototype more, please go ahead too ;)

Edit:

Even using:

Object.prototype.test = function() {
    return 2 + 2;
};

I still get that error in the console. I thought that all objects would inherit that prototype function too.

Upvotes: 2

Views: 50

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

You can think of prototype functions and values as default values for all instances. Why you're seeing the TypeError is because you're trying to call danys prototype and the method test() on that.

Try dany.test() instead.

This would be your best bet when reading on how it works.

TLDR;

You're getting the TypeError because the instance of the user function doesn't have its own prototype. You can however access the instances prototype via the __proto__ shortcut.

Upvotes: 5

Related Questions