1

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?

strider
  • 5,674
  • 4
  • 24
  • 29
  • duplicate https://stackoverflow.com/questions/36719481/virtual-function-in-javascript – li_ Nov 15 '17 at 07: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 Nov 15 '17 at 07:48

1 Answers1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Ah, so all JavaScript functions are virtual function in the sense that they can be inherited and overridden, but not in the sense that they are defined as belonging to a castable type; there are no types, and so there can be no dynamic dispatch. – strider Nov 15 '17 at 16:48
  • 1
    @bitstrider: Pretty much, yup. Objects arguably have a type of sorts, but references do not (and thus no dynamic dispatch in the comp sci sense). – T.J. Crowder Nov 15 '17 at 16:53