JavaScript override methods

Viewed 186326

Let's say you have the below code:

function A() {
    function modify() {
       x = 300;
       y = 400;
    }

    var c = new C();
}

function B() {
    function modify(){
       x = 3000;
       y = 4000;
    }

    var c = new C();
}

C = function () {
   var x = 10;
   var y = 20;

   function modify() {
      x = 30;
      y = 40;
   };

   modify();
   alert("The sum is: " + (x+y));
}

Now the question is, if there is any way in which I can override the method modify from C with the methods that are in A and B. In Java you would use the super-keyword, but how can you achieve something like this in JavaScript?

7 Answers

function A() {
    var c = new C();
 c.modify = function(){
  c.x = 123;
  c.y = 333;
 }
 c.sum();
}

function B() {
    var c = new C();
 c.modify = function(){
  c.x = 999;
  c.y = 333;
 }
 c.sum();
}


C = function () {
   this.x = 10;
   this.y = 20;

   this.modify = function() {
      this.x = 30;
      this.y = 40;
   };
   
   this.sum = function(){
 this.modify();
 console.log("The sum is: " + (this.x+this.y));
   }
}

A();
B();

Related