The goal of this post is to compare some basics features of JavaScript with C#.
Objects Initialization
The initialization of JavaScript objects is similar to c# anonymous initialization.
// c# Anonymous initialization var car = new { Name = "myCar", PlateNumber = 12435 };
// JavaScript Initialization var car = { Name: "myCar", PlateNumber: 12435 };
Dynamic members
JavaScript objects can be dynamically expanded or updated. The behavior is like dynamic + ExpandoObjects in C#.
// c# Dynamic objects dynamic car = new ExpandoObject(); car.Name = "myCar"; car.PlateNumber = 1234;
// JavaScript objects var car = {} car.Name = "myCar"; car.PlateNumber = 12435;
Classes and object oriented programming
JavaScript is a function oriented language. This means that classes in JavaScript are fairly different to classes in c#.
A class in JavaScript looks like a function. We need to use the keyword ‘this’ inside a function to define fields and methods of our class and the keyword ‘new’ to create instances. The function itself is the constructor of the class.
// c# class Car myCar = new Car("myCar", "12345"); class Car { public Car(string name, string plateNumber) { this.Name = name; this.PlateNumber = plateNumber; } public string Name { get; set; } public string PlateNumber { get; set; } public void Move(object position) { // move } private int Speed = 50; }
// JavaScript class var car = new Car("myCar", 12345); function Car(name, plateNumber) { // public this.name = name; this.plateNumber = plateNumber; this.move = function (position) { /* move*/ } // private var speed = 50; }
Properties
The previous javascript code is not creating properties because they have no getter and setter, if we need the getter and setter methods we need to use the following special syntax. This syntax also allows to define read-only properties.
// private backing field var _name; // property with public getter and setter Object.defineProperty(this, "name", { get: function() { return _name; }, set: function(value) { _name = value; } });
Static methods and fields
Static members needs to be added dynamically to the class function:
// Define static field Car.wheels = 4; // Create instance var myCar = new Car("myCar", 12345); // Use static field var test = myCar.wheels; // ERROR, static methods cannot be called from an instance var test = Car.wheels; // OK
Prototype and inheritance
Prototype is an object contained by all classes. We can be extended dynamically this object (like all objects in JavaScript) with data and methods that will be accessible from our class.
Car.prototype.wheels = 4; Car.prototype.move = function(position) { /* move*/ };
Inheritance in JavaScript is implemented changing the prototype of the child class. Let’s create a class “Car” that should have “Vehicle” class as base class:
function Vehicle(...) { ... } function Car(...){ ... } Ferrari.prototype = new Vehicle();