What is "The" prototype? - javascript

I am trying to wrap my head around prototypes, and wold like to know what the prototype is exactly. Much of the confusion stems from not understanding the metalanguage used to describe
prototypes.
Here is what I know:
When we create a named constructor function with properties inside it, the properties inside the body of that constructor function are inherited by object instances created by that constructor function. Here I've created an instance called person001 from the constructor function named Person.
function Person(firstName,lastName) {
this.firstName = firstName;
this.lastName = lastName
}
undefined
var person001 = new Person("John","Doe");
When I look at the object instance in the console and trace the prototype chain, I find it in 2 different places. It is a constructor object of the dunder proto object...
Person {firstName: "John", lastName: "Doe"}
firstName: "John"
lastName: "Doe"
__proto__:
constructor: ƒ Person(firstName,lastName)
__proto__: Object
and a property of the prototype object inside of the same constructor object.
Person {firstName: "John", lastName: "Doe"}
firstName: "John"
lastName: "Doe"
__proto__:
constructor: ƒ Person(firstName,lastName)
arguments: null
caller: null
length: 2
name: "Person"
prototype:
constructor: ƒ Person(firstName,lastName)
__proto__: Object
__proto__: ƒ ()
[[FunctionLocation]]: script.js:76
[[Scopes]]: Scopes[1]
__proto__: Object
When I add a property using the .prototype property of the named constructor function, I am adding that property to the prototype object, NOT to the constructor function. The added property will sit alongside the constructor function in the object of the prototype property. Here I add a property called age using the prototype property of the constructor function Person.
Person.prototype.age = 0;
So now that I've added an additional property, what exactly is the prototype?
When I run the Object.getPrototypeOf method on the object instance person001 it returns what looks to me like the prototype object. It has 3 properties -- a constructor function, the property I added, and the implicit dunder proto object.
Object.getPrototypeOf(person001);
{age: 0, constructor: ƒ}
age: 0
constructor: ƒ Person(firstName,lastName)
__proto__: Object
So what is the prototype? Is it the prototype object {constructor function, additional properties}? Or is it just the constructor function of the prototype object?
Thanks in advance for your assistance.

When you do obj = new Person, there are three players in the game:
the freshly created object obj
the constructor function Person
the prototype, a special hidden object stored under Person.prototype
The relationships between them are as follows:
obj.__proto__ === Person.prototype
Person.prototype.constructor === Person
Illustration:
function Person(firstName,lastName) {
this.firstName = firstName;
this.lastName = lastName
}
var person1 = new Person("John","Doe");
var person2 = new Person("Ann","Smith");
Person.prototype.age = 42;

Said you have created a constructor for a Person and then two instances of it:
const Person = function(name) {
this.name = name;
this.speak = () => console.log('My name is ' + this.name)
};
const john = new Person('John');
const mary = new Person('Mary');
john.speak();
mary.speak();
Now each person you create has a different name, and they can both speak it because they share the same property from some parent object.
But Mary not only can speak. She can sing. But John cannot.
const Person = function(name) {
this.name = name;
this.speak = () => console.log('My name is ' + this.name)
};
const john = new Person('John');
const mary = new Person('Mary');
john.speak();
mary.speak();
mary.sing = () => console.log('♪♪♪ Lalalalalala ♪♪♪');
mary.sing();
john.sing(); // John is such a bad singer, that this throws an error !
What if later on you realize that your people do not only need to speak, but also to walk. You need a reference to their common parent in order to tell them to walk all in one line. That's the prototype. Both Mary and John share a common prototype and have, deep inside, a reference to that prototype (that's __proto__, for friends and family).
const Person = function(name) {
this.name = name;
this.speak = () => console.log('My name is ' + this.name)
};
const john = new Person('John');
const mary = new Person('Mary');
john.speak();
mary.speak();
Person.prototype.walk = () => console.log('I am walking alright');
john.walk();
mary.walk();
// That is the same as:
john.__proto__.walk()
mary.__proto__.walk()
Now John has a bad fall, and it has troubles walking
const Person = function(name) {
this.name = name;
this.speak = () => console.log('My name is ' + this.name)
};
const john = new Person('John');
const mary = new Person('Mary');
john.speak();
mary.speak();
Person.prototype.walk = () => console.log('I am walking alright');
// John's infamous accident
john.walk = () => console.log('My leg hurts so bad...');
john.walk();
mary.walk();
Instance has its own property, we use that.
It has not, we look in its __proto__, and use it if it exists.
Hope this helps!

EDIT: My friend #teemu added to my answer: Every inbuilt object has its prototype.
In very simple language, Every function is a special kind of object in javascript And every function has its own "prototype" object container.
So every constructor function will have its own "prototype" object, which will be shared with all objects in __proto__ constructed using this.
Let's see in example:
// constructor function:
var Person = function(name, age){
this.name = name;
this.age = age
}
var tony = new Person('tony', 21);
var bruce = new Person('bruce', 22);
so as we discussed,
Person.prototype should be the same as tony.__proto__ and bruce.__proto__
note: you can replace Person with inbuilt Array, Object or String also.
to verify this we can do this:
Person.prototype == tony.__proto__; //true
Person.prototype == bruce.__proto__; //true
bruce.__proto__ == tony.__proto__; //true
next thing we are going to do add one property on bruce.__proto__:
bruce.__proto__.isSuperHero = true;
it is same thing when you add properties in prototype
but this will be reflected everywhere;
console.log(tony.__proto__.isSuperHero ) // true
console.log(Person.prototype.isSuperHero) //true
Now you can imagine a prototype as a common space like a house for all family members if any of the family members make changes in that house it will be changed for everyone and every family member can access the house no matter how old he is or he is just a newborn. it will be the same for every family members, stairs will be same, the rooms will be same, the color of the walls will be same.
I hope this will help you in understanding prototype chaining, I tried to explain it in different way which is a better way in my view.

First of all, prototype is just an object. Almost every object in JS (except for eg. when you use Object.create(null)) has some prototype and the prototypes can be chained.
Example: When you create an array by using literal [], your array instance is connected to object (also array instance btw.) defining array's properties like map etc., which itself is connected to another prototype (object instance) defining properties of objects like toString. Those properties are usually functions. Now when you access one of the properties of your object like [].hasOwnProperty, the engine looks up the prototype chain to find it. It start at your [] instance, doesn't find it, continues to the prototype (the array), also without success, so moves to the last prototype (object instance) where it is finally found.
As you can see, prototype chain always ends somewhere, so if you try to retrieve prototype on the last prototype in the chain, you will get null.
Now back to the constructor functions. First thing to note is that those are just normal functions - the actual "creator" of the instance is the keyword new. Now every function has a prototype property which tells you this: Every object created by using this function will get prototype-connected to whatever is in the function's prototype property. By default, every function contains instance of Object in this property, which means that every object you create from this function will be prototype-connected to this instance and will therefore "inherit" properties like toString.
You can see the connection between function's prototype property and instance's prototype in this example.
function A() {}
var a = new A();
a.__proto__ == A.prototype; // is true
Last, the constructor property in the function's prototype property tells you, which function will be used to create new instances when using the function with the new keyword. This mouthful boils down to:
function A() {}
A == A.prototype.constructor; // is true
It is a reference to itself. This property was optional to set when creating your own inheritance chain prior to ES6, but was done nevertheless for correctness' sake.
So what is prototype? It is just an object, connected to other object instances via a special prototype connection, giving it access to predefined properties. It is a way to do inheritance in JS.

Related

How do Javascript object instances retain methods after parent class is redefined?

I am trying to understand Javascript prototypal inheritance and am having trouble understanding the relationship between object instances and their respective classes' prototype property which stores inherited methods.
I understand that defining methods in a class's prototype property allows for instances to access/inherit these methods so that methods are not redefined. Presumably this is achieved by allowing the instance a pointer to the method in memory (or something much akin to this). I also understand why adding methods to a class's prototype property allows previously created instances access to these "new" methods, since the instances are simply accessing their prototype property (which includes the class they derive from) which in turn accesses the class's prototype property.
What I do not understand is the following scenario:
I define a trivial object with method:
function Person(name) {
this.name = name;
}
Person.prototype.greeting = function() {
return "Hello, " + this.name;
}
I create an instance and can access data:
var p = new Person("Ryan");
p.name //"Ryan"
p.greeting() //"Hello, Ryan"
I redefine Person without greeting:
Person = function (name) {
this.name = name;
}
I can still use the greeting on the previous instance:
p.greeting() //"Hello, Ryan" but expected error
If as Person is being redefined it overwrites the prior Person constructor in memory, how is it that the instance "p" can still access the greeting method if there is no longer any such method associated with Person? Is it the case that instances actually copy the location of their inherited classes' methods in their own prototype field? If this is the case, why is it that there is always talk of a "prototype chain" that the processor must "walk up" to find inherited methods if the instance stores the location of these methods directly in their own prototype field?
Help is much appreciated. I apologize if there is something simple that I missed.
You are mixing up names which point to objects and the objects themselves. When you use:
Person = function (name) {
this.name = name;
}
you are not redefining the object that the name Person points to. You are just taking the name Person and pointing it to a new thing — a new function. The old Person.protoype is still in memory and the instance p holds a reference to it and p.constructor still points to the original Person function.
You can confirm this by grabbing a reference of the Person.prototype and comparing before and after the reassignment of the variable Person
function Person(name) {
this.name = name;
}
Person.prototype.greeting = function() {
return "Hello, " + this.name;
}
var p = new Person("Ryan");
// p's prototype is Person.prototype
console.log(Object.getPrototypeOf(p) === Person.prototype) // true
// grab a reference of the protoype for later
let Pprotot = Person.prototype
// point variable Person at something else
Person = function (name) {
this.name = name;
}
// p's prototype is STILL the old Person.prototype
console.log(Object.getPrototypeOf(p) === Pprotot) // still true
// p also still holds a reference to the old function (through the prototype)
console.log(p.constructor)
// but it's not the same thing the variable Person now points to
console.log(p.constructor === Person)
I just did a little test and it seems like the variable p is still remembering the previous object.
Person = function(name) {
this.name = name;
}
const s = new Person('hello');
s.name; //hello
s.greeting(); //s.greeting is not a function

Javascript prototype constructor - Why should I fix it? [duplicate]

In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
Does this serve any important purpose? Is it okay to omit it?
It's not always necessary, but it does have its uses. Suppose we wanted to make a copy method on the base Person class. Like this:
// define the Person Class
function Person(name) {
this.name = name;
}
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
// define the Student class
function Student(name) {
Person.call(this, name);
}
// inherit Person
Student.prototype = Object.create(Person.prototype);
Now what happens when we create a new Student and copy it?
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => false
The copy is not an instance of Student. This is because (without explicit checks), we'd have no way to return a Student copy from the "base" class. We can only return a Person. However, if we had reset the constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
...then everything works as expected:
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => true
Does this serve any important purpose?
Yes and no.
In ES5 and earlier, JavaScript itself didn't use constructor for anything. It defined that the default object on a function's prototype property would have it and that it would refer back to the function, and that was it. Nothing else in the specification referred to it at all.
That changed in ES2015 (ES6), which started using it in relation to inheritance hierarchies. For instance, Promise#then uses the constructor property of the promise you call it on (via SpeciesConstructor) when building the new promise to return. It's also involved in subtyping arrays (via ArraySpeciesCreate).
Outside of the language itself, sometimes people would use it when trying to build generic "clone" functions or just generally when they wanted to refer to what they believed would be the object's constructor function. My experience is that using it is rare, but sometimes people do use it.
Is it okay to omit it?
It's there by default, you only need to put it back when you replace the object on a function's prototype property:
Student.prototype = Object.create(Person.prototype);
If you don't do this:
Student.prototype.constructor = Student;
...then Student.prototype.constructor inherits from Person.prototype which (presumably) has constructor = Person. So it's misleading. And of course, if you're subclassing something that uses it (like Promise or Array) and not using class¹ (which handles this for you), you'll want to make sure you set it correctly. So basically: It's a good idea.
It's okay if nothing in your code (or library code you use) uses it. I've always ensured it was correctly wired up.
Of course, with ES2015 (aka ES6)'s class keyword, most of the time we would have used it, we don't have to anymore, because it's handled for us when we do
class Student extends Person {
}
¹ "...if you're subclassing something that uses it (like Promise or Array) and not using class..." — It's possible to do that, but it's a real pain (and a bit silly). You have to use Reflect.construct.
TLDR; Not super necessary, but will probably help in the long run, and it is more accurate to do so.
NOTE: Much edited as my previous answer was confusingly written and had some errors that I missed in my rush to answer. Thanks to those who pointed out some egregious errors.
Basically, it's to wire subclassing up correctly in Javascript. When we subclass, we have to do some funky things to make sure that the prototypal delegation works correctly, including overwriting a prototype object. Overwriting a prototype object includes the constructor, so we then need to fix the reference.
Let's quickly go through how 'classes' in ES5 work.
Let's say you have a constructor function and its prototype:
//Constructor Function
var Person = function(name, age) {
this.name = name;
this.age = age;
}
//Prototype Object - shared between all instances of Person
Person.prototype = {
species: 'human',
}
When you call the constructor to instantiate, say Adam:
// instantiate using the 'new' keyword
var adam = new Person('Adam', 19);
The new keyword invoked with 'Person' basically will run the Person constructor with a few additional lines of code:
function Person (name, age) {
// This additional line is automatically added by the keyword 'new'
// it sets up the relationship between the instance and the prototype object
// So that the instance will delegate to the Prototype object
this = Object.create(Person.prototype);
this.name = name;
this.age = age;
return this;
}
/* So 'adam' will be an object that looks like this:
* {
* name: 'Adam',
* age: 19
* }
*/
If we console.log(adam.species), the lookup will fail at the adam instance, and look up the prototypal chain to its .prototype, which is Person.prototype - and Person.prototype has a .species property, so the lookup will succeed at Person.prototype. It will then log 'human'.
Here, the Person.prototype.constructor will correctly point to Person.
So now the interesting part, the so-called 'subclassing'. If we want to create a Student class, that is a subclass of the Person class with some additional changes, we'll need to make sure that the Student.prototype.constructor points to Student for accuracy.
It doesn't do this by itself. When you subclass, the code looks like this:
var Student = function(name, age, school) {
// Calls the 'super' class, as every student is an instance of a Person
Person.call(this, name, age);
// This is what makes the Student instances different
this.school = school
}
var eve = new Student('Eve', 20, 'UCSF');
console.log(Student.prototype); // this will be an empty object: {}
Calling new Student() here would return an object with all of the properties we want. Here, if we check eve instanceof Person, it would return false. If we try to access eve.species, it would return undefined.
In other words, we need to wire up the delegation so that eve instanceof Person returns true and so that instances of Student delegate correctly to Student.prototype, and then Person.prototype.
BUT since we're calling it with the new keyword, remember what that invocation adds? It would call Object.create(Student.prototype), which is how we set up that delegational relationship between Student and Student.prototype. Note that right now, Student.prototype is empty. So looking up .species an instance of Student would fail as it delegates to only Student.prototype, and the .species property doesn't exist on Student.prototype.
When we do assign Student.prototype to Object.create(Person.prototype), Student.prototype itself then delegates to Person.prototype, and looking up eve.species will return human as we expect. Presumably we would want it to inherit from Student.prototype AND Person.prototype. So we need to fix all of that.
/* This sets up the prototypal delegation correctly
*so that if a lookup fails on Student.prototype, it would delegate to Person's .prototype
*This also allows us to add more things to Student.prototype
*that Person.prototype may not have
*So now a failed lookup on an instance of Student
*will first look at Student.prototype,
*and failing that, go to Person.prototype (and failing /that/, where do we think it'll go?)
*/
Student.prototype = Object.create(Person.prototype);
Now the delegation works, but we're overwriting Student.prototype with an of Person.prototype. So if we call Student.prototype.constructor, it would point to Person instead of Student. This is why we need to fix it.
// Now we fix what the .constructor property is pointing to
Student.prototype.constructor = Student
// If we check instanceof here
console.log(eve instanceof Person) // true
In ES5, our constructor property is a reference that refers to a function that we've written with the intent to be a 'constructor'. Aside from what the new keyword gives us, the constructor is otherwise a 'plain' function.
In ES6, the constructor is now built into the way we write classes - as in, it's provided as a method when we declare a class. This is simply syntactic sugar but it does accord us some conveniences like access to a super when we are extending an existing class. So we would write the above code like this:
class Person {
// constructor function here
constructor(name, age) {
this.name = name;
this.age = age;
}
// static getter instead of a static property
static get species() {
return 'human';
}
}
class Student extends Person {
constructor(name, age, school) {
// calling the superclass constructor
super(name, age);
this.school = school;
}
}
I'd disagree. It isn't necessary to set the prototype. Take that exact same code but remove the prototype.constructor line. Does anything change? No. Now, make the following changes:
Person = function () {
this.favoriteColor = 'black';
}
Student = function () {
Person.call(this);
this.favoriteColor = 'blue';
}
and at the end of the test code...
alert(student1.favoriteColor);
The color will be blue.
A change to the prototype.constructor, in my experience, doesn't do much unless you're doing very specific, very complicated things that probably aren't good practice anyway :)
Edit:
After poking around the web for a bit and doing some experimentation, it looks like people set the constructor so that it 'looks' like the thing that is being constructed with 'new'. I guess I would argue that the problem with this is that javascript is a prototype language - there is no such thing as inheritence. But most programmers come from a background of programming that pushes inheritence as 'the way'. So we come up with all sorts of things to try and make this prototypical language a 'classic' language.. such as extending 'classes'. Really, in the example they gave, a new student is a person - it isn't 'extending' from another student.. the student is all about the person, and whatever the person is the student is as well. Extend the student, and whatever you've extended is a student at heart, but is customized to fit your needs.
Crockford is a bit crazy and overzealous, but do some serious reading on some of the stuff that he's written.. it'll make you look at this stuff very differently.
This has the huge pitfall that if you wrote
Student.prototype.constructor = Student;
but then if there was a Teacher whose prototype was also Person and you wrote
Teacher.prototype.constructor = Teacher;
then the Student constructor is now Teacher!
Edit:
You can avoid this by ensuring that you had set the Student and Teacher prototypes using new instances of the Person class created using Object.create, as in the Mozilla example.
Student.prototype = Object.create(Person.prototype);
Teacher.prototype = Object.create(Person.prototype);
So far confusion is still there.
Following the original example, as you have an existing object student1 as:
var student1 = new Student("Janet", "Applied Physics");
Suppose you don't want to know how student1 is created, you just want another object like it, you can use the constructor property of student1 like:
var student2 = new student1.constructor("Mark", "Object-Oriented JavaScript");
Here it will fail to get the properties from Student if the constructor property is not set. Rather it will create a Person object.
Got a nice code example of why it is really necessary to set the prototype constructor..
function CarFactory(name){
this.name=name;
}
CarFactory.prototype.CreateNewCar = function(){
return new this.constructor("New Car "+ this.name);
}
CarFactory.prototype.toString=function(){
return 'Car Factory ' + this.name;
}
AudiFactory.prototype = new CarFactory(); // Here's where the inheritance occurs
AudiFactory.prototype.constructor=AudiFactory; // Otherwise instances of Audi would have a constructor of Car
function AudiFactory(name){
this.name=name;
}
AudiFactory.prototype.toString=function(){
return 'Audi Factory ' + this.name;
}
var myAudiFactory = new AudiFactory('');
alert('Hay your new ' + myAudiFactory + ' is ready.. Start Producing new audi cars !!! ');
var newCar = myAudiFactory.CreateNewCar(); // calls a method inherited from CarFactory
alert(newCar);
/*
Without resetting prototype constructor back to instance, new cars will not come from New Audi factory, Instead it will come from car factory ( base class ).. Dont we want our new car from Audi factory ????
*/
No need for sugared function 'classes' or using 'New' these days. Use object literals.
The Object prototype is already a 'class'. When you define an object literal, it is already an instance of the prototype Object. These can also act as another object's prototype, etc.
const Person = {
name: '[Person.name]',
greeting: function() {
console.log( `My name is ${ this.name || '[Name not assigned]' }` );
}
};
// Person.greeting = function() {...} // or define outside the obj if you must
// Object.create version
const john = Object.create( Person );
john.name = 'John';
console.log( john.name ); // John
john.greeting(); // My name is John
// Define new greeting method
john.greeting = function() {
console.log( `Hi, my name is ${ this.name }` )
};
john.greeting(); // Hi, my name is John
// Object.assign version
const jane = Object.assign( Person, { name: 'Jane' } );
console.log( jane.name ); // Jane
// Original greeting
jane.greeting(); // My name is Jane
// Original Person obj is unaffected
console.log( Person.name ); // [Person.name]
console.log( Person.greeting() ); // My name is [Person.name]
This is worth a read:
Class-based object-oriented languages, such as Java and C++, are
founded on the concept of two distinct entities: classes and
instances.
...
A prototype-based language, such as JavaScript, does not make this
distinction: it simply has objects. A prototype-based language has the
notion of a prototypical object, an object used as a template from
which to get the initial properties for a new object. Any object can
specify its own properties, either when you create it or at run time.
In addition, any object can be associated as the prototype for another
object, allowing the second object to share the first object's
properties
It is necessary when you need an alternative to toString without monkeypatching:
//Local
foo = [];
foo.toUpperCase = String(foo).toUpperCase;
foo.push("a");
foo.toUpperCase();
//Global
foo = [];
window.toUpperCase = function (obj) {return String(obj).toUpperCase();}
foo.push("a");
toUpperCase(foo);
//Prototype
foo = [];
Array.prototype.toUpperCase = String.prototype.toUpperCase;
foo.push("a");
foo.toUpperCase();
//toString alternative via Prototype constructor
foo = [];
Array.prototype.constructor = String.prototype.toUpperCase;
foo.push("a,b");
foo.constructor();
//toString override
var foo = [];
foo.push("a");
var bar = String(foo);
foo.toString = function() { return bar.toUpperCase(); }
foo.toString();
//Object prototype as a function
Math.prototype = function(char){return Math.prototype[char]};
Math.prototype.constructor = function()
{
var i = 0, unicode = {}, zero_padding = "0000", max = 9999;
while (i < max)
{
Math.prototype[String.fromCharCode(parseInt(i, 16))] = ("u" + zero_padding + i).substr(-4);
i = i + 1;
}
}
Math.prototype.constructor();
console.log(Math.prototype("a") );
console.log(Math.prototype["a"] );
console.log(Math.prototype("a") === Math.prototype["a"]);
EDIT, I was actually wrong. Commenting the line out doesn't change it's behavior at all. (I tested it)
Yes, it is necessary. When you do
Student.prototype = new Person();
Student.prototype.constructor becomes Person. Therefore, calling Student() would return an object created by Person. If you then do
Student.prototype.constructor = Student;
Student.prototype.constructor is reset back to Student. Now when you call Student() it executes Student, which calls the parent constructor Parent(), it returns the correctly inherited object. If you didn't reset Student.prototype.constructor before calling it you would get an object that would not have any of the properties set in Student().
Given simple constructor function:
function Person(){
this.name = 'test';
}
console.log(Person.prototype.constructor) // function Person(){...}
Person.prototype = { //constructor in this case is Object
sayName: function(){
return this.name;
}
}
var person = new Person();
console.log(person instanceof Person); //true
console.log(person.sayName()); //test
console.log(Person.prototype.constructor) // function Object(){...}
By default (from the specification https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor), all prototypes automatically get a property called constructor that points back to the function on which it is a property.
Depending on the constructor, other properties and methods might be added to the prototype which is not a very common practice but still it is allowed for extensions.
So simply answering: we need make sure that the value in prototype.constructor is correctly set as it is supposed by the specification to be.
Do we have to always set correctly this value? It helps with debugging and makes internal structure consistent against specification. We should definitely when our API is being used by the thirdparties, but not really when the code is finally executed in the runtime.
Here's one example from MDN which I found very helpful to understand its uses.
In JavaScript, we have async functions which returns AsyncFunction object. AsyncFunction is not a global object but one may retrieve it by using constructor property and utilize it.
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
// AsyncFunction constructor
var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
var a = new AsyncFunction('a',
'b',
'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
a(10, 20).then(v => {
console.log(v); // prints 30 after 4 seconds
});
It is necessary. Any class in class inheritance must has its own constructor, so as in prototype inheritance.It is also convenient for object construction. But the question is unnecessary and what is necessary is understanding in JavaScript world effect of calling function as constructor and rule of resolving object property.
Effect of executing function as constructor with expression new <function name>( [ parameters] )
a object whose type name is the function name is created
inner properties in the function attaches to the created object
property prototype of the function attaches automatically to the created object as prototype
Rule of resolving property of object
The property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
Basing on these underlying mechanisms, statement <constructor name>.prototype.constructor = <constructor name> equals in term of effect to attach constructor in constructor body with expression this.constructor = <constructor name>. The constructor will be resolved on the object if second utterance while on object's prototype if first utterance.
It is not necessary. It is just one of the many things traditional, OOP champions do to try to turn JavaScript's prototypical inheritance into classical inheritance. The only thing that the following
Student.prototype.constructor = Student;
does, is that you now have a reference of the current "constructor".
In Wayne's answer, that has been marked as correct, you could the exact same thing that the following code does
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
with the code below (just replace this.constructor with Person)
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new Person(this.name);
};
Thank God that with ES6 classical inheritance purists can use language's native operators like class, extends and super and we don't have to see like prototype.constructor corrections and parent refereces.

isPrototypeOf in Javascript

I am a beginner to JavaScript and on my way to Prototypes in JavaScript.
As per the article here
Creating a Prototype
The standard way to create an object prototype is to use an object constructor function:
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
With a constructor function, you can use the new keyword to create new objects from the same prototype:
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");
The constructor function is the prototype for your person objects.
I find myself confused at the above bold line, which I think is absolutely wrong.
Reason:
alert(person.isPrototypeOf(myFather)); // false
Am I correct to say this as I do believe in this line:
The ‘prototype’ property points to the object that will be assigned as the prototype
of instances created with that function when using ‘new’.
I would agree that terminology is incorrect.
The constructor function has a prototype property which defines the properties and methods in the prototype chain; but it is not itself the prototype of an object, it is the constructor.
isPrototypeOf is not called on the constructor itself, but on the constructor's prototype property.
alert(person.prototype.isPrototypeOf(myFather)); // true
myFather would be an instanceof person, and you can test this using the following line.
alert(myFather instanceof person); // true
I agree with you - the sentence "The constructor function is the prototype for your person objects" is confusing and inaccurate. Instead, your understanding is correct although let me elaborate more.
Basically, whenever you create a function in JavaScript, it will automatically have a property on it called .prototype and the value associated with it will be an object. In your case, the person function also has this .prototype property. When you create new instances of person, each instance will be set up as inheriting from the object associated with the person function's .prototype property - the instance's prototype. This inheritance means that property look-ups are delegated to this prototype object. The key here is that when your person instances look up a property, they will first look up the property on themselves, and if the property isn't found, they will go up the prototype chain.
Looking at your example, here is what is correct:
person.prototype.isPrototypeOf( new person() );
In other words, any instance of person knows to delegate to the object associated with person.prototype whenever the instance can't find a property on itself.
What you are saying,
The ‘prototype’ property points to the object that will be assigned as the prototype of instances created with that function when using ‘new’.
Doesn't make much sense to me, but I think you've got the right idea.
To me, at least,
The constructor function is the prototype for your person objects.
is wrong.
The correct version would be:
The constructor function is the constructor function for your person objects.
The prototype property of your constructor function is an object.
It contains properties which are assigned to objects instantiated with that constructor function, example:
function Person(name){
this.name = name;
}
Person.prototype = {
species: "Human"
};
Sets up a constructor function with a prototype property, containing a property species.
Now, if we do this:
var joe = new Person("Joe");
joe is an object which looks like
{
name: "Joe",
species: "Human"
}
As you can see, the properties of the prototype of Person() were set as normal properties of Joe.
TL;DR
So I think you had the right idea.

Inheritance using Object.create [duplicate]

In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
Does this serve any important purpose? Is it okay to omit it?
It's not always necessary, but it does have its uses. Suppose we wanted to make a copy method on the base Person class. Like this:
// define the Person Class
function Person(name) {
this.name = name;
}
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
// define the Student class
function Student(name) {
Person.call(this, name);
}
// inherit Person
Student.prototype = Object.create(Person.prototype);
Now what happens when we create a new Student and copy it?
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => false
The copy is not an instance of Student. This is because (without explicit checks), we'd have no way to return a Student copy from the "base" class. We can only return a Person. However, if we had reset the constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
...then everything works as expected:
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => true
Does this serve any important purpose?
Yes and no.
In ES5 and earlier, JavaScript itself didn't use constructor for anything. It defined that the default object on a function's prototype property would have it and that it would refer back to the function, and that was it. Nothing else in the specification referred to it at all.
That changed in ES2015 (ES6), which started using it in relation to inheritance hierarchies. For instance, Promise#then uses the constructor property of the promise you call it on (via SpeciesConstructor) when building the new promise to return. It's also involved in subtyping arrays (via ArraySpeciesCreate).
Outside of the language itself, sometimes people would use it when trying to build generic "clone" functions or just generally when they wanted to refer to what they believed would be the object's constructor function. My experience is that using it is rare, but sometimes people do use it.
Is it okay to omit it?
It's there by default, you only need to put it back when you replace the object on a function's prototype property:
Student.prototype = Object.create(Person.prototype);
If you don't do this:
Student.prototype.constructor = Student;
...then Student.prototype.constructor inherits from Person.prototype which (presumably) has constructor = Person. So it's misleading. And of course, if you're subclassing something that uses it (like Promise or Array) and not using class¹ (which handles this for you), you'll want to make sure you set it correctly. So basically: It's a good idea.
It's okay if nothing in your code (or library code you use) uses it. I've always ensured it was correctly wired up.
Of course, with ES2015 (aka ES6)'s class keyword, most of the time we would have used it, we don't have to anymore, because it's handled for us when we do
class Student extends Person {
}
¹ "...if you're subclassing something that uses it (like Promise or Array) and not using class..." — It's possible to do that, but it's a real pain (and a bit silly). You have to use Reflect.construct.
TLDR; Not super necessary, but will probably help in the long run, and it is more accurate to do so.
NOTE: Much edited as my previous answer was confusingly written and had some errors that I missed in my rush to answer. Thanks to those who pointed out some egregious errors.
Basically, it's to wire subclassing up correctly in Javascript. When we subclass, we have to do some funky things to make sure that the prototypal delegation works correctly, including overwriting a prototype object. Overwriting a prototype object includes the constructor, so we then need to fix the reference.
Let's quickly go through how 'classes' in ES5 work.
Let's say you have a constructor function and its prototype:
//Constructor Function
var Person = function(name, age) {
this.name = name;
this.age = age;
}
//Prototype Object - shared between all instances of Person
Person.prototype = {
species: 'human',
}
When you call the constructor to instantiate, say Adam:
// instantiate using the 'new' keyword
var adam = new Person('Adam', 19);
The new keyword invoked with 'Person' basically will run the Person constructor with a few additional lines of code:
function Person (name, age) {
// This additional line is automatically added by the keyword 'new'
// it sets up the relationship between the instance and the prototype object
// So that the instance will delegate to the Prototype object
this = Object.create(Person.prototype);
this.name = name;
this.age = age;
return this;
}
/* So 'adam' will be an object that looks like this:
* {
* name: 'Adam',
* age: 19
* }
*/
If we console.log(adam.species), the lookup will fail at the adam instance, and look up the prototypal chain to its .prototype, which is Person.prototype - and Person.prototype has a .species property, so the lookup will succeed at Person.prototype. It will then log 'human'.
Here, the Person.prototype.constructor will correctly point to Person.
So now the interesting part, the so-called 'subclassing'. If we want to create a Student class, that is a subclass of the Person class with some additional changes, we'll need to make sure that the Student.prototype.constructor points to Student for accuracy.
It doesn't do this by itself. When you subclass, the code looks like this:
var Student = function(name, age, school) {
// Calls the 'super' class, as every student is an instance of a Person
Person.call(this, name, age);
// This is what makes the Student instances different
this.school = school
}
var eve = new Student('Eve', 20, 'UCSF');
console.log(Student.prototype); // this will be an empty object: {}
Calling new Student() here would return an object with all of the properties we want. Here, if we check eve instanceof Person, it would return false. If we try to access eve.species, it would return undefined.
In other words, we need to wire up the delegation so that eve instanceof Person returns true and so that instances of Student delegate correctly to Student.prototype, and then Person.prototype.
BUT since we're calling it with the new keyword, remember what that invocation adds? It would call Object.create(Student.prototype), which is how we set up that delegational relationship between Student and Student.prototype. Note that right now, Student.prototype is empty. So looking up .species an instance of Student would fail as it delegates to only Student.prototype, and the .species property doesn't exist on Student.prototype.
When we do assign Student.prototype to Object.create(Person.prototype), Student.prototype itself then delegates to Person.prototype, and looking up eve.species will return human as we expect. Presumably we would want it to inherit from Student.prototype AND Person.prototype. So we need to fix all of that.
/* This sets up the prototypal delegation correctly
*so that if a lookup fails on Student.prototype, it would delegate to Person's .prototype
*This also allows us to add more things to Student.prototype
*that Person.prototype may not have
*So now a failed lookup on an instance of Student
*will first look at Student.prototype,
*and failing that, go to Person.prototype (and failing /that/, where do we think it'll go?)
*/
Student.prototype = Object.create(Person.prototype);
Now the delegation works, but we're overwriting Student.prototype with an of Person.prototype. So if we call Student.prototype.constructor, it would point to Person instead of Student. This is why we need to fix it.
// Now we fix what the .constructor property is pointing to
Student.prototype.constructor = Student
// If we check instanceof here
console.log(eve instanceof Person) // true
In ES5, our constructor property is a reference that refers to a function that we've written with the intent to be a 'constructor'. Aside from what the new keyword gives us, the constructor is otherwise a 'plain' function.
In ES6, the constructor is now built into the way we write classes - as in, it's provided as a method when we declare a class. This is simply syntactic sugar but it does accord us some conveniences like access to a super when we are extending an existing class. So we would write the above code like this:
class Person {
// constructor function here
constructor(name, age) {
this.name = name;
this.age = age;
}
// static getter instead of a static property
static get species() {
return 'human';
}
}
class Student extends Person {
constructor(name, age, school) {
// calling the superclass constructor
super(name, age);
this.school = school;
}
}
I'd disagree. It isn't necessary to set the prototype. Take that exact same code but remove the prototype.constructor line. Does anything change? No. Now, make the following changes:
Person = function () {
this.favoriteColor = 'black';
}
Student = function () {
Person.call(this);
this.favoriteColor = 'blue';
}
and at the end of the test code...
alert(student1.favoriteColor);
The color will be blue.
A change to the prototype.constructor, in my experience, doesn't do much unless you're doing very specific, very complicated things that probably aren't good practice anyway :)
Edit:
After poking around the web for a bit and doing some experimentation, it looks like people set the constructor so that it 'looks' like the thing that is being constructed with 'new'. I guess I would argue that the problem with this is that javascript is a prototype language - there is no such thing as inheritence. But most programmers come from a background of programming that pushes inheritence as 'the way'. So we come up with all sorts of things to try and make this prototypical language a 'classic' language.. such as extending 'classes'. Really, in the example they gave, a new student is a person - it isn't 'extending' from another student.. the student is all about the person, and whatever the person is the student is as well. Extend the student, and whatever you've extended is a student at heart, but is customized to fit your needs.
Crockford is a bit crazy and overzealous, but do some serious reading on some of the stuff that he's written.. it'll make you look at this stuff very differently.
This has the huge pitfall that if you wrote
Student.prototype.constructor = Student;
but then if there was a Teacher whose prototype was also Person and you wrote
Teacher.prototype.constructor = Teacher;
then the Student constructor is now Teacher!
Edit:
You can avoid this by ensuring that you had set the Student and Teacher prototypes using new instances of the Person class created using Object.create, as in the Mozilla example.
Student.prototype = Object.create(Person.prototype);
Teacher.prototype = Object.create(Person.prototype);
So far confusion is still there.
Following the original example, as you have an existing object student1 as:
var student1 = new Student("Janet", "Applied Physics");
Suppose you don't want to know how student1 is created, you just want another object like it, you can use the constructor property of student1 like:
var student2 = new student1.constructor("Mark", "Object-Oriented JavaScript");
Here it will fail to get the properties from Student if the constructor property is not set. Rather it will create a Person object.
Got a nice code example of why it is really necessary to set the prototype constructor..
function CarFactory(name){
this.name=name;
}
CarFactory.prototype.CreateNewCar = function(){
return new this.constructor("New Car "+ this.name);
}
CarFactory.prototype.toString=function(){
return 'Car Factory ' + this.name;
}
AudiFactory.prototype = new CarFactory(); // Here's where the inheritance occurs
AudiFactory.prototype.constructor=AudiFactory; // Otherwise instances of Audi would have a constructor of Car
function AudiFactory(name){
this.name=name;
}
AudiFactory.prototype.toString=function(){
return 'Audi Factory ' + this.name;
}
var myAudiFactory = new AudiFactory('');
alert('Hay your new ' + myAudiFactory + ' is ready.. Start Producing new audi cars !!! ');
var newCar = myAudiFactory.CreateNewCar(); // calls a method inherited from CarFactory
alert(newCar);
/*
Without resetting prototype constructor back to instance, new cars will not come from New Audi factory, Instead it will come from car factory ( base class ).. Dont we want our new car from Audi factory ????
*/
No need for sugared function 'classes' or using 'New' these days. Use object literals.
The Object prototype is already a 'class'. When you define an object literal, it is already an instance of the prototype Object. These can also act as another object's prototype, etc.
const Person = {
name: '[Person.name]',
greeting: function() {
console.log( `My name is ${ this.name || '[Name not assigned]' }` );
}
};
// Person.greeting = function() {...} // or define outside the obj if you must
// Object.create version
const john = Object.create( Person );
john.name = 'John';
console.log( john.name ); // John
john.greeting(); // My name is John
// Define new greeting method
john.greeting = function() {
console.log( `Hi, my name is ${ this.name }` )
};
john.greeting(); // Hi, my name is John
// Object.assign version
const jane = Object.assign( Person, { name: 'Jane' } );
console.log( jane.name ); // Jane
// Original greeting
jane.greeting(); // My name is Jane
// Original Person obj is unaffected
console.log( Person.name ); // [Person.name]
console.log( Person.greeting() ); // My name is [Person.name]
This is worth a read:
Class-based object-oriented languages, such as Java and C++, are
founded on the concept of two distinct entities: classes and
instances.
...
A prototype-based language, such as JavaScript, does not make this
distinction: it simply has objects. A prototype-based language has the
notion of a prototypical object, an object used as a template from
which to get the initial properties for a new object. Any object can
specify its own properties, either when you create it or at run time.
In addition, any object can be associated as the prototype for another
object, allowing the second object to share the first object's
properties
It is necessary when you need an alternative to toString without monkeypatching:
//Local
foo = [];
foo.toUpperCase = String(foo).toUpperCase;
foo.push("a");
foo.toUpperCase();
//Global
foo = [];
window.toUpperCase = function (obj) {return String(obj).toUpperCase();}
foo.push("a");
toUpperCase(foo);
//Prototype
foo = [];
Array.prototype.toUpperCase = String.prototype.toUpperCase;
foo.push("a");
foo.toUpperCase();
//toString alternative via Prototype constructor
foo = [];
Array.prototype.constructor = String.prototype.toUpperCase;
foo.push("a,b");
foo.constructor();
//toString override
var foo = [];
foo.push("a");
var bar = String(foo);
foo.toString = function() { return bar.toUpperCase(); }
foo.toString();
//Object prototype as a function
Math.prototype = function(char){return Math.prototype[char]};
Math.prototype.constructor = function()
{
var i = 0, unicode = {}, zero_padding = "0000", max = 9999;
while (i < max)
{
Math.prototype[String.fromCharCode(parseInt(i, 16))] = ("u" + zero_padding + i).substr(-4);
i = i + 1;
}
}
Math.prototype.constructor();
console.log(Math.prototype("a") );
console.log(Math.prototype["a"] );
console.log(Math.prototype("a") === Math.prototype["a"]);
EDIT, I was actually wrong. Commenting the line out doesn't change it's behavior at all. (I tested it)
Yes, it is necessary. When you do
Student.prototype = new Person();
Student.prototype.constructor becomes Person. Therefore, calling Student() would return an object created by Person. If you then do
Student.prototype.constructor = Student;
Student.prototype.constructor is reset back to Student. Now when you call Student() it executes Student, which calls the parent constructor Parent(), it returns the correctly inherited object. If you didn't reset Student.prototype.constructor before calling it you would get an object that would not have any of the properties set in Student().
Given simple constructor function:
function Person(){
this.name = 'test';
}
console.log(Person.prototype.constructor) // function Person(){...}
Person.prototype = { //constructor in this case is Object
sayName: function(){
return this.name;
}
}
var person = new Person();
console.log(person instanceof Person); //true
console.log(person.sayName()); //test
console.log(Person.prototype.constructor) // function Object(){...}
By default (from the specification https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor), all prototypes automatically get a property called constructor that points back to the function on which it is a property.
Depending on the constructor, other properties and methods might be added to the prototype which is not a very common practice but still it is allowed for extensions.
So simply answering: we need make sure that the value in prototype.constructor is correctly set as it is supposed by the specification to be.
Do we have to always set correctly this value? It helps with debugging and makes internal structure consistent against specification. We should definitely when our API is being used by the thirdparties, but not really when the code is finally executed in the runtime.
Here's one example from MDN which I found very helpful to understand its uses.
In JavaScript, we have async functions which returns AsyncFunction object. AsyncFunction is not a global object but one may retrieve it by using constructor property and utilize it.
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
// AsyncFunction constructor
var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
var a = new AsyncFunction('a',
'b',
'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
a(10, 20).then(v => {
console.log(v); // prints 30 after 4 seconds
});
It is necessary. Any class in class inheritance must has its own constructor, so as in prototype inheritance.It is also convenient for object construction. But the question is unnecessary and what is necessary is understanding in JavaScript world effect of calling function as constructor and rule of resolving object property.
Effect of executing function as constructor with expression new <function name>( [ parameters] )
a object whose type name is the function name is created
inner properties in the function attaches to the created object
property prototype of the function attaches automatically to the created object as prototype
Rule of resolving property of object
The property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
Basing on these underlying mechanisms, statement <constructor name>.prototype.constructor = <constructor name> equals in term of effect to attach constructor in constructor body with expression this.constructor = <constructor name>. The constructor will be resolved on the object if second utterance while on object's prototype if first utterance.
It is not necessary. It is just one of the many things traditional, OOP champions do to try to turn JavaScript's prototypical inheritance into classical inheritance. The only thing that the following
Student.prototype.constructor = Student;
does, is that you now have a reference of the current "constructor".
In Wayne's answer, that has been marked as correct, you could the exact same thing that the following code does
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
with the code below (just replace this.constructor with Person)
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new Person(this.name);
};
Thank God that with ES6 classical inheritance purists can use language's native operators like class, extends and super and we don't have to see like prototype.constructor corrections and parent refereces.

Why is it necessary to set the prototype constructor?

In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
Does this serve any important purpose? Is it okay to omit it?
It's not always necessary, but it does have its uses. Suppose we wanted to make a copy method on the base Person class. Like this:
// define the Person Class
function Person(name) {
this.name = name;
}
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
// define the Student class
function Student(name) {
Person.call(this, name);
}
// inherit Person
Student.prototype = Object.create(Person.prototype);
Now what happens when we create a new Student and copy it?
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => false
The copy is not an instance of Student. This is because (without explicit checks), we'd have no way to return a Student copy from the "base" class. We can only return a Person. However, if we had reset the constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
...then everything works as expected:
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => true
Does this serve any important purpose?
Yes and no.
In ES5 and earlier, JavaScript itself didn't use constructor for anything. It defined that the default object on a function's prototype property would have it and that it would refer back to the function, and that was it. Nothing else in the specification referred to it at all.
That changed in ES2015 (ES6), which started using it in relation to inheritance hierarchies. For instance, Promise#then uses the constructor property of the promise you call it on (via SpeciesConstructor) when building the new promise to return. It's also involved in subtyping arrays (via ArraySpeciesCreate).
Outside of the language itself, sometimes people would use it when trying to build generic "clone" functions or just generally when they wanted to refer to what they believed would be the object's constructor function. My experience is that using it is rare, but sometimes people do use it.
Is it okay to omit it?
It's there by default, you only need to put it back when you replace the object on a function's prototype property:
Student.prototype = Object.create(Person.prototype);
If you don't do this:
Student.prototype.constructor = Student;
...then Student.prototype.constructor inherits from Person.prototype which (presumably) has constructor = Person. So it's misleading. And of course, if you're subclassing something that uses it (like Promise or Array) and not using class¹ (which handles this for you), you'll want to make sure you set it correctly. So basically: It's a good idea.
It's okay if nothing in your code (or library code you use) uses it. I've always ensured it was correctly wired up.
Of course, with ES2015 (aka ES6)'s class keyword, most of the time we would have used it, we don't have to anymore, because it's handled for us when we do
class Student extends Person {
}
¹ "...if you're subclassing something that uses it (like Promise or Array) and not using class..." — It's possible to do that, but it's a real pain (and a bit silly). You have to use Reflect.construct.
TLDR; Not super necessary, but will probably help in the long run, and it is more accurate to do so.
NOTE: Much edited as my previous answer was confusingly written and had some errors that I missed in my rush to answer. Thanks to those who pointed out some egregious errors.
Basically, it's to wire subclassing up correctly in Javascript. When we subclass, we have to do some funky things to make sure that the prototypal delegation works correctly, including overwriting a prototype object. Overwriting a prototype object includes the constructor, so we then need to fix the reference.
Let's quickly go through how 'classes' in ES5 work.
Let's say you have a constructor function and its prototype:
//Constructor Function
var Person = function(name, age) {
this.name = name;
this.age = age;
}
//Prototype Object - shared between all instances of Person
Person.prototype = {
species: 'human',
}
When you call the constructor to instantiate, say Adam:
// instantiate using the 'new' keyword
var adam = new Person('Adam', 19);
The new keyword invoked with 'Person' basically will run the Person constructor with a few additional lines of code:
function Person (name, age) {
// This additional line is automatically added by the keyword 'new'
// it sets up the relationship between the instance and the prototype object
// So that the instance will delegate to the Prototype object
this = Object.create(Person.prototype);
this.name = name;
this.age = age;
return this;
}
/* So 'adam' will be an object that looks like this:
* {
* name: 'Adam',
* age: 19
* }
*/
If we console.log(adam.species), the lookup will fail at the adam instance, and look up the prototypal chain to its .prototype, which is Person.prototype - and Person.prototype has a .species property, so the lookup will succeed at Person.prototype. It will then log 'human'.
Here, the Person.prototype.constructor will correctly point to Person.
So now the interesting part, the so-called 'subclassing'. If we want to create a Student class, that is a subclass of the Person class with some additional changes, we'll need to make sure that the Student.prototype.constructor points to Student for accuracy.
It doesn't do this by itself. When you subclass, the code looks like this:
var Student = function(name, age, school) {
// Calls the 'super' class, as every student is an instance of a Person
Person.call(this, name, age);
// This is what makes the Student instances different
this.school = school
}
var eve = new Student('Eve', 20, 'UCSF');
console.log(Student.prototype); // this will be an empty object: {}
Calling new Student() here would return an object with all of the properties we want. Here, if we check eve instanceof Person, it would return false. If we try to access eve.species, it would return undefined.
In other words, we need to wire up the delegation so that eve instanceof Person returns true and so that instances of Student delegate correctly to Student.prototype, and then Person.prototype.
BUT since we're calling it with the new keyword, remember what that invocation adds? It would call Object.create(Student.prototype), which is how we set up that delegational relationship between Student and Student.prototype. Note that right now, Student.prototype is empty. So looking up .species an instance of Student would fail as it delegates to only Student.prototype, and the .species property doesn't exist on Student.prototype.
When we do assign Student.prototype to Object.create(Person.prototype), Student.prototype itself then delegates to Person.prototype, and looking up eve.species will return human as we expect. Presumably we would want it to inherit from Student.prototype AND Person.prototype. So we need to fix all of that.
/* This sets up the prototypal delegation correctly
*so that if a lookup fails on Student.prototype, it would delegate to Person's .prototype
*This also allows us to add more things to Student.prototype
*that Person.prototype may not have
*So now a failed lookup on an instance of Student
*will first look at Student.prototype,
*and failing that, go to Person.prototype (and failing /that/, where do we think it'll go?)
*/
Student.prototype = Object.create(Person.prototype);
Now the delegation works, but we're overwriting Student.prototype with an of Person.prototype. So if we call Student.prototype.constructor, it would point to Person instead of Student. This is why we need to fix it.
// Now we fix what the .constructor property is pointing to
Student.prototype.constructor = Student
// If we check instanceof here
console.log(eve instanceof Person) // true
In ES5, our constructor property is a reference that refers to a function that we've written with the intent to be a 'constructor'. Aside from what the new keyword gives us, the constructor is otherwise a 'plain' function.
In ES6, the constructor is now built into the way we write classes - as in, it's provided as a method when we declare a class. This is simply syntactic sugar but it does accord us some conveniences like access to a super when we are extending an existing class. So we would write the above code like this:
class Person {
// constructor function here
constructor(name, age) {
this.name = name;
this.age = age;
}
// static getter instead of a static property
static get species() {
return 'human';
}
}
class Student extends Person {
constructor(name, age, school) {
// calling the superclass constructor
super(name, age);
this.school = school;
}
}
I'd disagree. It isn't necessary to set the prototype. Take that exact same code but remove the prototype.constructor line. Does anything change? No. Now, make the following changes:
Person = function () {
this.favoriteColor = 'black';
}
Student = function () {
Person.call(this);
this.favoriteColor = 'blue';
}
and at the end of the test code...
alert(student1.favoriteColor);
The color will be blue.
A change to the prototype.constructor, in my experience, doesn't do much unless you're doing very specific, very complicated things that probably aren't good practice anyway :)
Edit:
After poking around the web for a bit and doing some experimentation, it looks like people set the constructor so that it 'looks' like the thing that is being constructed with 'new'. I guess I would argue that the problem with this is that javascript is a prototype language - there is no such thing as inheritence. But most programmers come from a background of programming that pushes inheritence as 'the way'. So we come up with all sorts of things to try and make this prototypical language a 'classic' language.. such as extending 'classes'. Really, in the example they gave, a new student is a person - it isn't 'extending' from another student.. the student is all about the person, and whatever the person is the student is as well. Extend the student, and whatever you've extended is a student at heart, but is customized to fit your needs.
Crockford is a bit crazy and overzealous, but do some serious reading on some of the stuff that he's written.. it'll make you look at this stuff very differently.
This has the huge pitfall that if you wrote
Student.prototype.constructor = Student;
but then if there was a Teacher whose prototype was also Person and you wrote
Teacher.prototype.constructor = Teacher;
then the Student constructor is now Teacher!
Edit:
You can avoid this by ensuring that you had set the Student and Teacher prototypes using new instances of the Person class created using Object.create, as in the Mozilla example.
Student.prototype = Object.create(Person.prototype);
Teacher.prototype = Object.create(Person.prototype);
So far confusion is still there.
Following the original example, as you have an existing object student1 as:
var student1 = new Student("Janet", "Applied Physics");
Suppose you don't want to know how student1 is created, you just want another object like it, you can use the constructor property of student1 like:
var student2 = new student1.constructor("Mark", "Object-Oriented JavaScript");
Here it will fail to get the properties from Student if the constructor property is not set. Rather it will create a Person object.
Got a nice code example of why it is really necessary to set the prototype constructor..
function CarFactory(name){
this.name=name;
}
CarFactory.prototype.CreateNewCar = function(){
return new this.constructor("New Car "+ this.name);
}
CarFactory.prototype.toString=function(){
return 'Car Factory ' + this.name;
}
AudiFactory.prototype = new CarFactory(); // Here's where the inheritance occurs
AudiFactory.prototype.constructor=AudiFactory; // Otherwise instances of Audi would have a constructor of Car
function AudiFactory(name){
this.name=name;
}
AudiFactory.prototype.toString=function(){
return 'Audi Factory ' + this.name;
}
var myAudiFactory = new AudiFactory('');
alert('Hay your new ' + myAudiFactory + ' is ready.. Start Producing new audi cars !!! ');
var newCar = myAudiFactory.CreateNewCar(); // calls a method inherited from CarFactory
alert(newCar);
/*
Without resetting prototype constructor back to instance, new cars will not come from New Audi factory, Instead it will come from car factory ( base class ).. Dont we want our new car from Audi factory ????
*/
No need for sugared function 'classes' or using 'New' these days. Use object literals.
The Object prototype is already a 'class'. When you define an object literal, it is already an instance of the prototype Object. These can also act as another object's prototype, etc.
const Person = {
name: '[Person.name]',
greeting: function() {
console.log( `My name is ${ this.name || '[Name not assigned]' }` );
}
};
// Person.greeting = function() {...} // or define outside the obj if you must
// Object.create version
const john = Object.create( Person );
john.name = 'John';
console.log( john.name ); // John
john.greeting(); // My name is John
// Define new greeting method
john.greeting = function() {
console.log( `Hi, my name is ${ this.name }` )
};
john.greeting(); // Hi, my name is John
// Object.assign version
const jane = Object.assign( Person, { name: 'Jane' } );
console.log( jane.name ); // Jane
// Original greeting
jane.greeting(); // My name is Jane
// Original Person obj is unaffected
console.log( Person.name ); // [Person.name]
console.log( Person.greeting() ); // My name is [Person.name]
This is worth a read:
Class-based object-oriented languages, such as Java and C++, are
founded on the concept of two distinct entities: classes and
instances.
...
A prototype-based language, such as JavaScript, does not make this
distinction: it simply has objects. A prototype-based language has the
notion of a prototypical object, an object used as a template from
which to get the initial properties for a new object. Any object can
specify its own properties, either when you create it or at run time.
In addition, any object can be associated as the prototype for another
object, allowing the second object to share the first object's
properties
It is necessary when you need an alternative to toString without monkeypatching:
//Local
foo = [];
foo.toUpperCase = String(foo).toUpperCase;
foo.push("a");
foo.toUpperCase();
//Global
foo = [];
window.toUpperCase = function (obj) {return String(obj).toUpperCase();}
foo.push("a");
toUpperCase(foo);
//Prototype
foo = [];
Array.prototype.toUpperCase = String.prototype.toUpperCase;
foo.push("a");
foo.toUpperCase();
//toString alternative via Prototype constructor
foo = [];
Array.prototype.constructor = String.prototype.toUpperCase;
foo.push("a,b");
foo.constructor();
//toString override
var foo = [];
foo.push("a");
var bar = String(foo);
foo.toString = function() { return bar.toUpperCase(); }
foo.toString();
//Object prototype as a function
Math.prototype = function(char){return Math.prototype[char]};
Math.prototype.constructor = function()
{
var i = 0, unicode = {}, zero_padding = "0000", max = 9999;
while (i < max)
{
Math.prototype[String.fromCharCode(parseInt(i, 16))] = ("u" + zero_padding + i).substr(-4);
i = i + 1;
}
}
Math.prototype.constructor();
console.log(Math.prototype("a") );
console.log(Math.prototype["a"] );
console.log(Math.prototype("a") === Math.prototype["a"]);
EDIT, I was actually wrong. Commenting the line out doesn't change it's behavior at all. (I tested it)
Yes, it is necessary. When you do
Student.prototype = new Person();
Student.prototype.constructor becomes Person. Therefore, calling Student() would return an object created by Person. If you then do
Student.prototype.constructor = Student;
Student.prototype.constructor is reset back to Student. Now when you call Student() it executes Student, which calls the parent constructor Parent(), it returns the correctly inherited object. If you didn't reset Student.prototype.constructor before calling it you would get an object that would not have any of the properties set in Student().
Given simple constructor function:
function Person(){
this.name = 'test';
}
console.log(Person.prototype.constructor) // function Person(){...}
Person.prototype = { //constructor in this case is Object
sayName: function(){
return this.name;
}
}
var person = new Person();
console.log(person instanceof Person); //true
console.log(person.sayName()); //test
console.log(Person.prototype.constructor) // function Object(){...}
By default (from the specification https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor), all prototypes automatically get a property called constructor that points back to the function on which it is a property.
Depending on the constructor, other properties and methods might be added to the prototype which is not a very common practice but still it is allowed for extensions.
So simply answering: we need make sure that the value in prototype.constructor is correctly set as it is supposed by the specification to be.
Do we have to always set correctly this value? It helps with debugging and makes internal structure consistent against specification. We should definitely when our API is being used by the thirdparties, but not really when the code is finally executed in the runtime.
Here's one example from MDN which I found very helpful to understand its uses.
In JavaScript, we have async functions which returns AsyncFunction object. AsyncFunction is not a global object but one may retrieve it by using constructor property and utilize it.
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
// AsyncFunction constructor
var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
var a = new AsyncFunction('a',
'b',
'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
a(10, 20).then(v => {
console.log(v); // prints 30 after 4 seconds
});
It is necessary. Any class in class inheritance must has its own constructor, so as in prototype inheritance.It is also convenient for object construction. But the question is unnecessary and what is necessary is understanding in JavaScript world effect of calling function as constructor and rule of resolving object property.
Effect of executing function as constructor with expression new <function name>( [ parameters] )
a object whose type name is the function name is created
inner properties in the function attaches to the created object
property prototype of the function attaches automatically to the created object as prototype
Rule of resolving property of object
The property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
Basing on these underlying mechanisms, statement <constructor name>.prototype.constructor = <constructor name> equals in term of effect to attach constructor in constructor body with expression this.constructor = <constructor name>. The constructor will be resolved on the object if second utterance while on object's prototype if first utterance.
It is not necessary. It is just one of the many things traditional, OOP champions do to try to turn JavaScript's prototypical inheritance into classical inheritance. The only thing that the following
Student.prototype.constructor = Student;
does, is that you now have a reference of the current "constructor".
In Wayne's answer, that has been marked as correct, you could the exact same thing that the following code does
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
with the code below (just replace this.constructor with Person)
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new Person(this.name);
};
Thank God that with ES6 classical inheritance purists can use language's native operators like class, extends and super and we don't have to see like prototype.constructor corrections and parent refereces.

Categories

Resources