Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the disadvantages of using constructors in js

Shulou Source: shulou.com Published: 2022-06-03 07:59:41 10月01日 Update

This article mainly introduces the shortcomings of js using constructors, the article is very detailed, has a certain reference value, interested friends must read it!

1. Instead of inheriting from the prototype chain, it just borrows the constructor, so you cannot inherit the properties and methods of the prototype.

2. Although the properties and methods defined in the constructor are accessible, each instance is copied.

If there are too many examples, too many methods, and a lot of memory, then the method is defined in the constructor, and the reuse of the function is out of the question.

Example

/ / parent constructor function Father () {this.name = 'father' this.speakName1 = function () {console.log (' speakName1')} this.speakName2 = function () {console.log ('speakName2')} this.speakName3 = function () {console.log (' speakName3')} this.speakName4 = function () {console.log () 'speakName4')}} / / method on parent prototype Father.prototype.alertName = function () {console.log (this.name)} / / attribute on parent prototype Father.prototype.age = 21G / child constructor function Children () {Father.call (this)} / / create child instance let C1 = new Children () / / call the prototype method Instance cannot access c1.alertName () / / TypeError: c1.alertName is not a function / / access prototype properties. Console.log (c1.age) / / undefined / / is not defined in the instance to access instance properties, but each instance has its own name value console.log (c1.name) / / father / / to access instance methods, but each instance has its own speakName1 () method, / / and there are too many methods C1.speakName1 () / / speakName1 c1.speakName2 () / / speakName2 c1.speakName3 () / / speakName3 c1.speakName4 () / / speakName4 / / instanceof isPrototypeOf cannot determine the relationship between instance and type console.log (Father.prototype.isPrototypeOf (C1)) / / falseconsole.log (C1 instanceof Father) / / false is above all the contents of the article "what are the disadvantages of js using constructors" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Instances methods functions prototypes properties shortcomings memory content articles reuse great out of the question value examples interest usage just guys buddies more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB MySQL Huawei Shulou Technology OPPO Reno