Javascript中的虚函数 [英] Virtual function in Javascript

查看:40
本文介绍了Javascript中的虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在问如何在C#之类的javascript中实现虚拟功能

I am asking how to implement the virtual function in the javascript like C#, let's say

  • 我有一个基类A
  • 我还有一个名为B的派生类
  • 类A有一个名为virtualFunction的函数,应该像在C#中那样是一个虚函数,可以在派生类B中覆盖它.
  • 该函数将被调用以在基类A的构造函数中执行.如果该函数在B中被覆盖,则将调用B的函数,否则将调用A的函数

在下面的示例中,我想获得"B"警报,而不是"A"警报.

With this example below, I want to get a 'B' alert, not the 'A'.

function A() {
  this.virtualFunction();
}

A.prototype.virtualFunction = function() {
  alert('A');
};

//-------------------------------------

function B() {}

B.prototype = new A();
B.prototype.virtualFunction = function() {
  alert('B');
};

var b = new B();

如果我们在实例化之后调用函数,就像这样,那没关系,但我需要在构造函数内部"

If we invoke the function after instanced, like this, then it is okay, but I need "inside the constructor"

var b = new B();
b.virtualFunction();

推荐答案

因此,首先要意识到的是JavaScript与C#使用的语义不同.试图这样做会导致您心痛;学习JS中的事情是更好的选择.实际上,大多数人并没有尝试在JS中做很多继承类型的事情,而是偏爱组合(这实际上是我所熟悉的所有OO语言中的最佳实践).

So, the first thing to realize is that JavaScript doesn't use the same semantics as C#. Trying to get it to do so will cause you heartache; you're much better off learning how things are done in JS. In fact, most folks don't try to do a lot of inheritance type stuff in JS, but instead favor composition (which is actually a best practice in all OO languages I'm familiar with).

也就是说,您可以对代码进行一些改进.

That said, there's a few improvements you could make to your code.

function A() {
  this.virtualFunction();
}

A.prototype.virtualFunction = function() {
  alert('A');
};

//-------------------------------------

function B() {
   A.call(this);
}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.virtualFunction = function() {
  alert('B');
};

var b = new B();

这篇关于Javascript中的虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆