Should I declare a prototype constructor in js?

<script> function User (theName, theEmail) { this.name = theName; this.email = theEmail; } User.prototype = { constructor: User, changeEmail:function (newEmail) { this.email = newEmail; return "New Email Saved: " + this.email; } } // A User firstUser = new User("Richard", " Richard@examnple.com "); firstUser.changeEmail(" RichardB@examnple.com "); </script> 

He took this code here: http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/

Question:

It is nessecerry to put this line: constructor: User, ,? If I delete this line, it will still work.

+4
source share
2 answers

When we create a new object in javascript using the new or {} operator, the new property of the constructor of the object points to the constructor function. In your case:

 firstUser = new User("Richard", " Richard@examnple.com "); 

firstUser.constructor - User . The same is true for your User.prototype . When you use {} to create a new object for User.prototype , the property of the Object constructor. When you put constructor: User , you simply change the constructor property from Object to User , and your code still works.

+2
source

You only need to do this if you replace the default prototype with a new object, as you do with User.prototype = {...} . Instead, you can simply extend the default prototype:

 User.prototype.changeEmail = function (newEmail) { this.email = newEmail; return "New Email Saved: " + this.email; } 
0
source

Source: https://habr.com/ru/post/1486737/


All Articles