2

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.