Friday, April 19, 2013

C# and JavaScript - Inheritance Examples

JavaScript uses prototypal inheritance, which is different from what we are used to in C#, Java, etc.

You can accomplish the same thing in Javascript, but with different syntax.


// JS Inheritable Class
function Animal(){
 
 this.animal_name = "";
 
 this.lengthOfToes = [];
 
 this.hasClaws = false;
 
}

// JS Inheritable Class, alternative format
var Animal = function(){};  // empty function
Animal.prototype.animal_name = "";
Animal.prototype.lengthOfToes = [];
Animal.prototype.hasClaws = false;


// creating an instance of an object
var Lion = new Animal();

// extending it
Lion.prototype.hasMane = true;

// JS Object Literal, NOT inheritable
var Animal = {

 animal_name: "Simba",
 
 lengthOfToes: [2,3,3,3,2,3,2,4,2,3],
 
 hasClaws: false
 
};

// C#
public virtual class Animal
{
 public string animal_name { get; set; }
 int[] arrProp = new int[]();
}

public partial class Lion : Animal
{
 public bool hasMane = new bool();
}


No comments:

Post a Comment