0

According to this page of W3 Schools, an object prototype is the constructor function that creates an object(Please mention if I have incorrectly interpreted this). And, according to one of my Javascript books, prototype is an object itself. But, when I do this:

JS:

function helloObject(name , id , age){
    this.name = name;
    this.id = id;
    this.age = age;
}

document.getElementById("testElement").textContent = typeof helloObject;//returns function

I get that prototype is nothing but the constructor function. So, which one of the two arguments is correct?

1
  • 1
    W3Schools is entirely wrong to lump the prototype and the constructor together. W3S is often wrong, you shouldn't rely in them too much at all. Commented Feb 21, 2016 at 13:14

1 Answer 1

3

Constructor is a function. That's why typeof helloObject return function. Every function has a property called "prototype". This prototype property is an object. You can check it out writing helloObject.prototype. But, prototype object is used only when you are using your function(in your case helloObject) as a constructor, i.e. with keyword new. So when you run var obj = new helloObject(), you have a new object in obj variable and this object has your name, id, age properties. But implicitly, javascript writes __proto__ property in you new object and assigns prototype property of the constructor to __proto__. Check this out in your console:

function helloObject(name) {
    this.name = name;
}
var obj = new helloObject('Your name');

console.log(helloObject.prototype)
console.log(obj.__proto__)
console.log(helloObject.prototype === obj.__proto__) // = true

Prototype property of the function usually used for inheritance in javascript. Here is couple of posts that can help understand prototype better:

http://code.tutsplus.com/tutorials/prototypes-in-javascript--net-24949

https://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/

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.