Looking at Languages (C#, Javascript & Ruby) 3: Classes

Javascript does not have classes in the traditional sense, but we can achieve something similar in a number of ways. C# and Ruby both have standard class syntax.

This post is part of a series comparing the language features of the C#, Javascript and Ruby programming languages.

C#

 

public class Vehicle
{
protected string Make { get; private set; }
protected string Model { get; private set; }

public Vehicle(string make, string model)
{
Make
= make;
Model
= model;
}

public virtual void Print()
{
Console.WriteLine(GetDescription());
}

protected string GetDescription()
{
// string formatting syntax return string.Format("Make: {0} Model: {1}", Make, Model);
}
}

public class Helicopter : Vehicle // inheritance syntax {
public int NumberOfRotorBlades { get; private set; }

public Helicopter(int numberOfRotorBlades, string make, string model)
:
base(make, model)
{
NumberOfRotorBlades
= numberOfRotorBlades;
}

public override void Print()
{
// string concatenation syntax Console.WriteLine(GetDescription() + " Number of Rotor Blades:" + NumberOfRotorBlades);
}
}

 

Javascript

Class:

// declare vehicle 'class' var vehicle = function(seed) {
var that = {};

// private method var getDescription = function() {
return "Make: " + seed.make + " Model: " + seed.model;
};

// public method that.print = function() {
alert(getDescription());
};

return that;
};

// instantiate a vehicle var magna = vehicle({
make:
'Mitsubishi',
model:
'Magna' }); magna.print();

Derived class:

 // declare helicopter 'class' var helicopter = function(seed) {
var that = {};
that.prototype
= vehicle(seed);

var getDescription = function() {
return "Make: " + seed.make + " Model: " + seed.model;
};

that.print
= function() {
alert(getDescription()
+ " Number of Rotor Blades:" + seed.numberOfRotorBlades);
};

return that;
};

// instantiate a helicopter var ah64 = helicopter({
make:
'Hughes Helicopters',
model:
'AH-64',
numberOfRotorBlades:
4 }); ah64.print();

Ruby

 class Vehicle    def initialize(make, model)     @make = make;
@model = model;
end

def print
puts get_description
end

private

def get_description
return
"Make: #{@make} Model: #{@model}" end end magna = Vehicle.new('Mitsubishi', 'Magna')
magna.print

class Helicopter < Vehicle

def initialize(make, model, number_of_rotors)
super(make, model)
@number_of_rotors = number_of_rotors
end

def print
puts get_description +
" Number of Rotors: #{@number_of_rotors}" end end ah64 = Helicopter.new("Hughes Helicopters", "AH-64", 4)
ah64.print

Comments

Comments are closed