简体   繁体   中英

Is there anything similar to JavaScript's “prototype” in Java?

Right, so I know Java fairly well but I never studied extensively into JavaScript. I was chatting with an acquaintance who knows JavaScript, but who has not studied into Java. He was telling me about the advantages of JavaScript over Java in terms of how it functions but not its uses.

Specifically, he was telling me about "prototyping" and what he explained seems to be the concepts of polymorphism and inheritance, but classless. Is this true?

I told this person that it seems this way, and he told me that prototyping is nothing at all like inheritance or polymorphism, and he told me to research it. Google isn't helping me out much in terms of comparing the two languages so I'm here in hopes of finding someone who knows both and can shed some light here.

It is similar in a sense of prototype is a parent for all objects aka functions in javascript that inherit from it. Java inheritance is much more well defined in extending objects and using interfaces and abstract classes. Javascript has low type abstraction. Everything is a function. Everything can have properties tacked on at will. There is no defined inheritance. If you follow a stack trace of a call in JavaScript it starts at the top most function and goes down to the prototype until it finds the call your looking for. Java on the other hand will look at the direct function or variable call and return. It will also traverse but upwards towards the Object parent. Everything in JavaScript is based off of function while in Java all objects are based off of Object.

Polymorphism is achieved by calls on Object.create in JavaScript vs just extending in Java. OOJS is way different in prototypical inheritance vs object inheritance. In Java

Javascript is a functional language so objects in Javascript are created by functions. Java is Object oriented to functions (methods) belong to objects.

Java script is also dynamically typed so objects get a type at runtime and do have some element of inheritance and polymorphism but it is not enforced through a static typing system like java's classes.

Prototyping is associated with the process of writing a function to create a new object of a particular type and declaring that an existing type is the prototype of the new type.

The new type will have all the properties of the old type plus any newly declared ones. So it is sort of like inheritance and polymorphism but the is no typing to enforce it so all you will get at runtime if you step outside the definition of a class is a undefined value.

From a use perspective the client code of any object can regard it as any prototype up the chain so yes inheritance and polymorphism.

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