oop - What are virtual functions in javascript? - Stack Overflow

admin2025-04-19  0

According to one definition of virtual functions:

In object-oriented programming, in languages such as C++, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated.

How would this look for functions in javascript?

According to one definition of virtual functions:

In object-oriented programming, in languages such as C++, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated.

How would this look for functions in javascript?

Share asked Nov 15, 2017 at 7:26 striderstrider 5,9944 gold badges26 silver badges30 bronze badges 2
  • duplicate stackoverflow./questions/36719481/… – li_ Commented Nov 15, 2017 at 7:45
  • @bee: Not really. That question asks how to do a virtual function, and the only answer to it says "don't", that the semantics are different (without going into details), and then makes small changes to the implementation in the question. That answer doesn't address this question's question, which is the dupe criterion. – T.J. Crowder Commented Nov 15, 2017 at 7:48
Add a ment  | 

1 Answer 1

Reset to default 7

How would this look for functions in javascript?

The concept largely doesn't apply to JavaScript.

The concept of virtual and non-virtual functions (methods, really) requires the concept of a type of reference to an object, as distinct from what the object is. For instance, you might have a BaseFoo type with a bar method, and a DerivedFoo type that derives from it and overrides bar. Later, if you have a BaseFoo-typed variable b referring to a DerivedFoo object, when you call b.bar(), you'll get DerivedFoo's bar if bar is virtual, but BaseFoo's bar if bar is non-virtual. But if you have a DerivedFoo-typed variable d referring to a DerivedFoo object, d.bar() always calls bar whether it's virtual or not. The type of the variable you're using to refer to the object determines what method gets called if the method is non-virtual.

None of that exists in JavaScript. References to objects are untyped. When you call o.bar(), you get the property bar from that object and call the function it refers to.

If you wanted to stretch a point, given JavaScript's prototypical inheritance mechanism, you could say that in some sense, all JavaScript "methods" are virtual, if we very loosely say a "method" is a function attached to an object property (although in ES2015+, "method" has a more specific meaning in JavaScript than that, but still fits that definition). That's because when you look up a property on an object, if it has its own property with that name, that's the one you get; you only get the one from its prototype if it doesn't have its own. But that's probably stretching a point, perhaps too far.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745073233a283412.html

最新回复(0)