codetalker
codetalker

Reputation: 586

What is prototype? Constructor function or a different object?

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?

Upvotes: 0

Views: 55

Answers (1)

aprok
aprok

Reputation: 1157

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/

Upvotes: 3

Related Questions