简体   繁体   中英

What are the technical advantages of pseudoclassical inheritance over functional inheritance (factory functions)?

Alternate title: "Why do so many popular JavaScript libraries use pseudoclassical inheritance as opposed to functional inheritance (factory functions)?"

JavaScript: The Good Parts advises the use of factory functions so that you get true privacy of methods and properties. This makes sense, so I'm wondering why so many modern JS libraries still use psuedoclassical inheritance (using the new keyword). Is there some technical advantage of going this route as opposed to factory functions? If not, is it just a stylistic choice?

EDIT: This is not an opinion-based post. I'm not asking which is better, I'm asking what technical advantages pseudoclassical inheritance has over functional to gain an understanding why someone would choose that style.

EDIT 2: A couple advantages of pseudoclassical I can see:

  1. When you console.log an instance of a prototype, it shows you the name of the object it was instanced from.
  2. On a related note, you can use instanceof to see if an instance came from a particular object, which is not possible with factory functions.

Let's focus in on your example. I don't think factory functions are required, though they can be preferred for the reason you stated. You can for instance have information hiding along with new, using the revealing module pattern.

Here's a link to a reasonable explanation of that pattern. http://jargon.js.org/_glossary/REVEALING_MODULE_PATTERN.md

I think it's really just a preference for one pattern over another in this case revealing pattern vs factory. it is likely that people's information is siloed and different theories are dominant in different places. You're only catching a part of the debate and wondering why everyone is not doing X over Y, they're mostly trying to satisfy similar concerns.

You'll find plenty of avoidance of new in statically typed languages where dependencies become more of a concern due to strong typing. You'll also get different answers from a functional programmer vs a procedural programming vs an OOP. I think one interesting aspect of javascript is it brings people from every type of language background to it.

I do also think that people are putting a lot more emphasis on composition rather than inheritance, with regards to javascript. React is a great example of that type of advocacy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM