Trying to understand the difference between prototype and constructor in JavaScript

javascript prototype
javascript prototype explained
difference between prototype and object in javascript
javascript prototype inheritance
javascript constructor
javascript copy constructor
javascript call prototype function in constructor
javascript class constructor

I'm new to JavaScript ,to understand this concept i have read many articles regarding prototype and constructors but where ever i go i'm left with confusion.

The confusion arises when people talk about constructor and prototype simultaneously.

In the following example

var employee = function Emp(name) {
    this.name = name;
}
var jack = new employee("Jack Dwain");

employee.constructor //gives Function()

employee.prototype // gives  Emp {}

employee.prototype.constructor //gives Emp(name)

jack.constructor //gives Emp(name)

jack.prototype //gives undefined
  1. prototype is a way JS achieves inheritance,since Emp(name) is the base function prototype is referenced to the same function itself. Is that what happened?

  2. In what way employee.constructor and employee.prototype.constructor differ?

  3. Why was jack.prototype is undefined i.e If it is inheriting from the function Emp(name) why it didn't reference that function?

  4. How can I clearly predict myself without typing in the console what the prototype or the constructor or the prototype.constructor ......yields

Trying to understand the difference between prototype and , I'm new to JavaScript ,to understand this concept i have read many articles regarding prototype and constructors but where ever i go i'm left with� Function.prototype === Function.constructor // returns false, Function.constructor is function Function(){} Most of the time you don't want to be middling with the native prototypes since modifying them will make all the objects that inherit from that prototype be modified as well.

If you want to create a javascript object you can simply declare a new object and give it properties (I've chosen to objectify myself):

var myself= {
    name:"Niddro",
    age:32
};

This method allows you to make one object. If what you want to have is a prototype describing a person in general, where you can declare several people with the same setup. To create a prototype, you can use a constructor, as seen below:

//Constructor
function generalNameForObject(param1, param2,...) {
    //Give the object some properties...
}

I have a prototype (a recipe) in mind that I want to call person and it should contain the properties name and age and I'll use a constructor to make it:

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

The above construct function describes the prototype for my person objects.

Create a new person by calling the construct function:

var myself = new person("Niddro",31);
var OP = new person("rajashekar thirumala",23);

Some time passes and I realise that I've had a birthday so I need to change the property of the prototype:

myself.age=32;

If you want to add properties to the construct, you need to manually add it into the construct function:

function person(name,age,rep) {
    this.name=name;
    this.age=age;
    this.reputation=rep;
}

Instead, you can add properties to the prototype by doing the following (here "prototype" is an actual command and not just a name):

function person(name,age,rep) {
    this.name=name;
    this.age=age;
}
person.prototype.reputation=105;

note that this will add a reputation of 105 for all objects created.

I hope this has given you some more insight on the relationship between the constructor and prototype.

Methods Within Constructor vs Prototype in Javascript, One scenario is when adding methods to your Javascript 'classes'. with an object instance of that constructor, pretty much like a static method. you must also know that any method attached via this will get re-declared for every new in the speed of invoking a method in comparison to the first approach. The JavaScript prototype chain is a little different than how most languages work, so it can be tricky understand. It doesn’t make it any easier when JavaScript gets syntax that makes it looks more like other languages, like inheriting Java’s new operator. But if you know what you’re doing, you can do some crazy-cool things with it.

employee.constructor //gives Function()

In JavaScript functions are also objects, which can be constructed using its own constructor which is Function . So you can write following code to get a instance of Function.

var employee2 = new Function('a', 'b', 'return a+b');

Same happens when you create function using function literal like in your case. And the constructor property of this object also refers to the same native Function object/class.

employee.prototype // gives Emp {}

Each object in JavaScript has a prototype associated with it. Though only function objects prototype is directly accessible with the .prototype. This same prototype is copied on its objects prototype when you create objects with new keyword. Primarily this copying is responsible for the inheritance/extension. Although the prototype is copied, it is not directly asseccible like in case of Function objects. It's available in non standard way with .__proto__ . Following code will return true.

jack.__proto__==employee.prototype

employee.prototype.constructor //gives Emp(name)

As said in the documentation of Object.prototype.constructor . This returns a reference to the Object function that created the instance's prototype. Here the object being refered is employee.prototype and not employee. This is bit complex but prototype of object employee.prototype was created by the function Emp(name)

jack.constructor //gives Emp(name)

As said in the previous point, this objects prototype was created by function Emp(name) when you created the object using new Emp(),

jack.prototype //gives undefined

jack is not a function object, so you cant access its prototype like that. You can access(not a standard way) the prototype of jack like following.

jack.__proto__

Master the JavaScript Interview: What's the Difference Between , Objects are frequently used in JavaScript, and understanding how to work with them effectively will The ES6 `class` keyword desugars to a constructor function: Prototypal Inheritance: A prototype is a working object instance. He works anywhere he wants with the most beautiful woman in the world. Take a look at the following image, taken from the following answer: When you create a new function, JavaScript automatically creates a new object (the prototype) as well: JavaScript sets the prototype property of the constructor function to the prototype object.

Constructor:

function Foo(x) {
    this.x =x;
}

Foo is the constructor. A constructor is a function.

There are two ways to use this constructor Foo.

"Objects are created by using constructors in new expressions; for example, new Date(2009,11) creates a new Date object. Invoking a constructor without using new has consequences that depend on the constructor. For example, Date() produces a string representation of the current date and time rather than an object."

Source ECMA-262

That means if Foo returns something (via return "somevalue";) then typeof Foo() is the type of the return value.

On the other hand, when you call

var o = new Foo();

JavaScript actually just does

var o = new Object();
o.[[Prototype]] = Foo.prototype;
Foo.call(o);

Prototype:

When you call o.a, then javascript first checks if a is a own property of the object o. If not javascript will look up the property chain to find a.

For more information about property-chain have a look at mdn.

The prototype porperty of the constructor has a really powerful feature, that is not available in classes. If it's useful is another debate. The prototype porperty of the constructor can alter properties of each instance that does link to that prototype in their prototype-chain.

TL,DR:

Note: This is not an exact definition, the purpose of the summary is just to give you a feeling about constructors and prototypes.

If you use a constructor with the new keyword, then constructors and prototypes have kind of similar purpose even though they are completely different. A constructor initializes properties of the object, so it provides properties. A prototype also provides properties via the property-chain (prototype-based inheritance).

All you need to know to understand JavaScript's Prototype, Most of the time, JavaScript's prototype confuses people who have just In this article, we will try to understand “prototypal inheritance” in JavaScript. Both are equivalent to each other with some differences that don't matter for this article. Now coming to the constructor function Array — it is a predefined� In reality, the only true difference between prototype and __proto__ is that the former is a property of a class constructor, while the latter is a property of a class instance. In other words

Yet the truth is, this approach might be wrong for many situations. In Javascript when you bind a method to the this keyword, you are providing that method to only that particular instance and it does not really have any relationship with an object instance of that constructor, pretty much like a static method. Keeping in mind that functions are first-class citizens in Javascript, we can deal with them just like objects, in this case we're only adding a property to an instance of a function object. Thats only part of the story, you must also know that any method attached via this will get re-declared for every new instance we create, which could affect the memory usage of the application negatively if we wish to create so many instances.

Object.prototype.constructor, The constructor property returns a reference to the Object constructor function that Objects created without the explicit use of a constructor function (such as object- and Let's try to define the cases in which re-assignment of the original The definition of 'Object.prototype.constructor' in that specification. Technically, JavaScript doesn’t have classes, but it has constructors and prototypes to bring similar functionality to JavaScript. In fact, the class declaration introduced in ES2015 simply works as syntactic sugar over the existing prototype-based inheritance and does not really add any extra functionality to the language.

Details of the object model, Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time. Constructor function or prototype� The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

Javascript Constructors and Prototypes, It turns out that if you return a value in a constructor, Javascript will Javascript is different from traditional object-oriented languages in that Now that you understand everything there is to know about prototype That doesn't work either, because it will first construct a person, and then try calling the apply� When it comes to the JavaScript Language comparing to other programming languages there are lots of worlds that you may hear or see really confusing to understand. One of them would be factory…

As a JS Developer, This Is What Keeps Me Up at Night, If you answered incorrectly, you don't understand what class actually is. It tries to hide the prototypical inheritance model and the clumsy idioms that come with it , The most important difference between class- and prototype-based inheritance A constructor in JavaScript is just a plain old function that returns an object. After creating the constructor function above and its instances, try to type the following in your browser console: person_a . __proto__ === Person . prototype // true Whenever we create a new instance of the Person constructor function through the new keyword, a reference to the prototype object of the constructor function gets added to the

Comments
  • I think the constructor is the function that you call to create the object. The prototype defines what the object can do. So the prototype is larger than the constructor. See also: Constructors in JavaScript.
  • This line: var employee = function Emp(name) { ... } is confusing. It would be better-written as function Emp(name) { ... } and only using Emp instead of employee.
  • Perhaps this answer will explain how prototypal inheritance works in JavaScript: stackoverflow.com/a/8096017/783743
  • I think it is better to observer __proto__ instead of prototype for research purpose. That will explain your last row output. i.e. jack.prototype //gives undefined
  • I hate Foo and Bar as example class an function names, even after 10 years of programming:-)
  • Well, puts on sunglasses deal with it :-p
  • I'm just thinking that when Foo Bar on it's own suffices that's fine, but if you need to use Title and Title.message as a follow on, then Foo and Bar should be replaced with a related metaphor
  • I did not understand "That is not what we want because now we cant access the message part in Title" until I understood that changing somethings prototype changes it's constructor to be the new prototype also. See second answer here: stackoverflow.com/questions/8093057/…
  • Yea, but I wrote in mind that anyone reading this understands inheritance in an OOP way. From an OOP perspective this is logical to me. but maybe i'm weird like that ;-)
  • it was a great practical explaination, thankyou. I am a beginner, and have also seen something called __proto__ being talked about in the similar context. is it same as person.prototype ?