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.