[英]What are virtual 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.
在面向对象的程序设计中,在C ++等语言中,虚函数或虚方法是可继承且可重写的函数或方法,因此有助于进行动态调度。
How would this look for functions in javascript? 这将如何寻找javascript中的函数?
How would this look for functions in javascript?
这将如何寻找javascript中的函数?
The concept largely doesn't apply to JavaScript. 该概念在很大程度上不适用于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
. 例如,你可能有一个
BaseFoo
与类型bar
法和DerivedFoo
,从它和重写派生类型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. 后来,如果你有一个
BaseFoo
-typed变量b
指的是DerivedFoo
对象,当你调用b.bar()
你会得到DerivedFoo
的bar
,如果bar
是虚拟的,但BaseFoo
的bar
,如果bar
是不虚。 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. 但是,如果您有一个
DerivedFoo
类型的变量d
引用了DerivedFoo
对象,则d.bar()
始终调用bar
无论它是否是虚拟的。 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. 这些都不存在于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. 调用
o.bar()
,您将从该对象获取属性bar
并调用其引用的函数。
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). 如果您想延伸一点,给定JavaScript的原型继承机制,您可以说从某种意义上说,所有JavaScript“方法”都是虚拟的,如果我们很宽松地说“方法”是附加到对象属性的函数(尽管ES2015 +中,“方法”在JavaScript中的含义比这更具体,但仍然符合该定义)。 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.
但这可能延伸了一点,也许太过分了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.