title: Virtual function in Javascript
body: <p>I am asking how to implement the virtual function in the javascript like C#, let's say </p>
  
  <ul>
  <li>I have a base class A</li>
  <li>I also have a derived class named B</li>
  <li>The class A has a function named virtualFunction, this is supposed to be a virtual function like in C#, this can be overridden in the derived class B</li>
  <li>The function will be called to execute inside the constructor of the base class, A. If the function is overridden in B, B's one will be invoked otherwise A's one will be invoked</li>
  </ul>
  
  <p>With this example below, I want to get a 'B' alert, not the 'A'. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>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();</code></pre>
  </div>
  </div>
  </p>
  
  <p>If we invoke the function after instanced, like this, then it is okay, but I need "inside the constructor"</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var b = new B();
  b.virtualFunction();</code></pre>
  </div>
  </div>
  </p>