Daniel Nastase Daniel Nastase - 2 months ago 17
Javascript Question

JavaScript override methods

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 wich 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?

Answer

JavaScript inheritance looks a bit different from Java. Here is how the native JavaScript object system looks:

// Create a class
function Vehicle(color){
  this.color = color;
}

// Add an instance method
Vehicle.prototype.go = function(){
  return "Underway in " + this.color;
}

// Add a second class
function Car(color){
  this.color = color;
}

// And declare it is a subclass of the first
Car.prototype = new Vehicle();

// Override the instance method
Car.prototype.go = function(){
  return Vehicle.prototype.go.call(this) + " car"
}

// Create some instances and see the overridden behavior.
var v = new Vehicle("blue");
v.go() // "Underway in blue"

var c = new Car("red");
c.go() // "Underway in red car"

Unfortunately this is a bit ugly and it does not include a very nice way to "super": you have to manually specify which parent classes' method you want to call. As a result, there are a variety of tools to make creating classes nicer. Try looking at Prototype.js, Backbone.js, or a similar library that includes a nicer syntax for doing OOP in js.