.




JavaScript in 60 minutes for C# developers




Part II




Frederic Torres 2011

Overview

Object Orientation And Inheritance

The Shortest Object Oriented Program In The World

Is this make any sense to you?

{ }

The Shortest Object Oriented Program In The World

Is this make any sense to you?

    p = { }

The Shortest Object Oriented Program In The World

Is this make any sense to you?

	var p = { }

The Shortest Object Oriented Program In The World

Semi colon are optional, but it is recommended to add them

	var p = { }; 

The Shortest Object Oriented Program In The World

C#
	var p = new { LastName = "Torres" };
    

JavaScript
	var p = { LastName : "Torres" };

Let's Create An Instance

C#
public class Person{
    public string LastName { get; set; }
    public Person(string lastName){
        this.LastName = lastName;
    }
    public void Run(){
        Console.WriteLine(this.LastName + " is running...");
    }
    static void Main(){
        var p = new Person("Torres");
        p.Run(); 
    }
}


JavaScript
var p = {
	LastName :  "Torres",
	run      :  function(){
                    print(this.LastName + " is running..."); 
                }
};
p.run();

Reflection vs Reflection On Steroid

C#
    const BindingFlags GET_FLAGS = BindingFlags.Instance | BindingFlags.Public | 
                                   BindingFlags.GetField | BindingFlags.GetProperty;

	var p = new { LastName = "Torres" };

    Console.WriteLine(p.LastName);

    Console.WriteLine(p.GetType().InvokeMember("LastName", GET_FLAGS, null, p, null));


JavaScript
    var p = { LastName   : "Torres" };

    print(p.LastName);

    print(p["LastName"]);    

Reflection vs Reflection On Steroid

C#
public class Program {

    static void Main(){

        var p = new { LastName = "Torres", FirstName = "Frederic" };

        foreach(var propertyInfo in p.GetType().GetProperties()){

            Console.WriteLine(propertyInfo.Name + " = " + propertyInfo.GetValue(p, null).ToString());
        }
    }
}

JavaScript
var p = { LastName : "Torres", FirstName : "Frederic" };

for(var propertyName in p){

    print(propertyName + " = " + p[propertyName]);
}

Class vs Function Constructor

C#
public class Person{

    public string LastName  { get; set; }
    public string FirstName { get; set; }

    public Person(string lastName, string firstName){
        this.LastName  = lastName;
        this.FirstName = firstName;
    }
    public void Run(){
        Console.WriteLine(this.LastName + " is running...");
    }
    static void Main(){
        var p = new Person("Torres", "Frederic");
        p.Run();
    }
}

JavaScript
function Person(lastName, firstName){

    this.LastName  = lastName;
    this.FirstName = firstName;

    this.run = function(){ // My prefered way to add method to an object
        print(this.LastName + " is running...");
    }
}
var p = new Person("Torres", "Frederic");
p.run();

Inheritance

C#
public class Employee : Person {  // (1) Inheritance

    public string Company  { get; set; }
    
    public Employee(string lastName, string firstName, string company)
                    :base(lastName, firstName) { // (2) Base constructor
        this.Company = company;
    }
    static void Main(){
        var e = new Employee("Torres", "Frederic", "ACompany");
        e.Run(); 
        Console.WriteLine(e is Person);
        Console.WriteLine(e is Employee);
    }
}


JavaScript
function Employee(lastName, firstName, company) {
     
    Person.call(this, lastName, firstName); // (2) Base constructor
    this.Company   = company;
}
Employee.prototype = new Person();  // (1) Inheritance

var e = new Employee("Torres", "Frederic", "ACompany");
e.run();
print(e instanceof Person);
print(e instanceof Employee);

Inheritance

Inheritance

Private Property

C#
public class Employee : Person {

    public string Company               { get; set; }
    private bool  _reservedParkingSpot  { get; set; }
    
    public Employee(string lastName, string firstName, string company, bool reservedParkingSpot)
                    :base(lastName,firstName) {
        this.Company              = company;
        this._reservedParkingSpot = reservedParkingSpot;
    }
    public override void Run(){
    
        Console.WriteLine(this.LastName + " reservedParkingSpot:" + _reservedParkingSpot);
    }
    static void Main(){
        var e = new Employee("Torres", "Frederic", "ACompany", true);
        e.Run();
    }
}

JavaScript
function Employee(lastName, firstName, company, reservedParkingSpot) {
    var
        _reservedParkingSpot = reservedParkingSpot;

    Person.call(this, lastName, firstName);
    this.Company = company;

    this.run = function() {
        print(this.LastName + " reservedParkingSpot:" + _reservedParkingSpot);
    }
}
Employee.prototype = new Person();
var e = new Employee("Torres", "Frederic", "ACompany", true);
e.run();

Miscellaneous

Static Member

C#
public class Person{

    public string LastName  { get; set; }
    public string FirstName { get; set; }

    public Person(string lastName, string firstName){
        this.LastName  = lastName;
        this.FirstName = firstName;
    }
    public static Person Create(string lastName, string firstName){
        return new Person(lastName, firstName);
    }
    static void Main(){
        var p = Person.Create("Torres", "Frederic");
    }
}

JavaScript
function Person(lastName, firstName){

    this.LastName  = lastName;
    this.FirstName = firstName;
}
Person.create = function(lastName, firstName){ // (X) Static Member 

    return new Person(lastName, firstName);
}
var p = Person.create("Torres", "Frederic");

Namespace

C#

namespace MyLibrary {
    public class Person{
        public string LastName  { get; set; }
        public string FirstName { get; set; }

        public Person(string lastName, string firstName){
            this.LastName  = lastName;
            this.FirstName = firstName;
        }
    }
}
public class Program{
    static void Main(){
        var p = new MyLibrary.Person("Torres", "Frederic");
    }
}

JavaScript
var MyLibrary = {
    Person : function (lastName, firstName){
        this.LastName  = lastName;
        this.FirstName = firstName;
    }
}
var p = new MyLibrary.Person("Torres", "Frederic");

Nested Namespace And Shortcut - ***

C#
using people = MyLibrary.People; 
namespace MyLibrary.People {
    public class Person{
        public string LastName  { get; set; }
        public string FirstName { get; set; }

        public Person(string lastName, string firstName){
            this.LastName  = lastName;
            this.FirstName = firstName;
        }
    }
}
public class Program{
    static void Main(){
        var p = new people.Person("Torres", "Frederic");
    }
}

JavaScript
var MyLibrary = { };
MyLibrary.People = {
    Person : function (lastName, firstName){
        this.LastName  = lastName;
        this.FirstName = firstName;
    }
}
var people = MyLibrary.People;
var p = new people.Person("Torres", "Frederic");

Enum Type

C#
public enum EmployeeType {
    Developer,
    Manager  ,
}
public class Employee : Person {

    public string Company    { get; set; }
    public EmployeeType Type { get; set; }
    
    public Employee(string lastName, string firstName, string company, EmployeeType type)
                    :base(lastName,firstName) {
        this.Company = company;
        this.Type    = type;
    }
    static void Main(){
        var e = new Employee("Torres", "Frederic", "ACompany", EmployeeType.Developer);
        e.Run();         
    }
}


JavaScript
var EmployeeType = {
    Developer : "Developer", // Why as string?
    Manager   : "Manager"  ,    
}
function Employee(lastName, firstName, company, type) {

    Person.call(this, lastName, firstName);
    this.Company = company;
    this.Type    = type;
}
Employee.prototype = new Person();

var e = new Employee("Torres", "Frederic", "ACompany", EmployeeType.Developer);
e.run();

.NET Attribute vs Function Property

C#
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class SuperMethodAttribute : System.Attribute {
}        
public class MyClass {    
    [SuperMethod]
    public void Run(){
    }
}       
public class Program {    
    public static string GetSuperMethodName(object o) {
        foreach (var mi in o.GetType().GetMembers())
            foreach (object attribute in mi.GetCustomAttributes(true))
                if (attribute is SuperMethodAttribute)
                    return mi.Name;
        return null;
    }
    static void Main() {
        var myClass = new MyClass();
        Console.WriteLine("The SuperMethod is " + GetSuperMethodName(myClass));
    }
}

JavaScript
function MyClass(){

    this.run = function(){

    }
    this.run.SuperMethod = true;
}
function GetSuperMethodName(o){
    for(var p in o)
        if(typeof o[p] ==="function") 
            if(o[p].SuperMethod===true)
                return p;
    return null;
}
var myClass = new MyClass();
print("The SuperMethod is " + GetSuperMethodName(myClass));

Other Miscellaneous

Data Structures

JavaScript Object vs Dictionary<K,V>

What is this ?

var trace = {

    On:true
}

JavaScript Object vs Dictionary<K,V>

C#
var trace = new Dictionary<string,object>();

trace["Debug"]     = true;
trace["Trace"]     = "warning";
trace["TraceSize"] = 1000;

foreach(var e in trace){
    Console.WriteLine(e.Key + " = " + e.Value.ToString());
}


JavaScript
var trace = { };

trace["Debug"]  = true;
trace["Trace"]  = "warning";
trace.TraceSize = 1000;

for(var key in trace){
    print(key + " = " + trace[key]);
}

JavaScript Object vs Dictionary<K,V>

C#
var trace = new Dictionary<string,object>() {
    { "Debug"    , true      },
    { "Trace"    , "warning" },
    { "TraceSize", 1000      }
};

if(trace.ContainsKey("Debug"))
    Console.WriteLine(trace["Debug"]);
    


JavaScript
var trace = {
    Debug     : true     ,
    Trace     : "warning",
    TraceSize : 1000
};

if("Debug" in trace)
    print(trace["Debug"]);

The Shortest Structured Program In The World

Is this make any sense to you?

[ ]

The Shortest Structured Program In The World

Is this make any sense to you?

var a = [ ];

The Shortest Structured Program In The World

var a = [ 1, 2, 3 ];

JavaScript Array

C#
var a = new List<object>();
 
var b = new List<int>() { 1, 2, 3 };

var c = new List<string>() { "a", "b", "c" };


JavaScript
var a = [ ];

var b = [ 1, 2, 3 ];

var c = [ "a", "b", "c" ];

What is a JavaScript Array? No Really!

Iterating Through An Array

C#
var a = new List<string>()  { "a", "b", "c" };

for(var i=0; i < a.Count; i++){
 
    Console.WriteLine(a[i]);
}

JavaScript
var a = [ "a", "b", "c" ];
 
for(var i=0; i < a.length; i++){
 
    print(a[i]);
}

Iterating Through An Array

C#
var a = new List<string>()  { "a", "b", "c" };

foreach(var i in a){
 
    Console.WriteLine(i);
}


JavaScript
var a = [ "a", "b", "c" ];
 
for(var i in a){
    
    print(a[i]);
}

Iterating Through An Array

C#
var a = new List<string>()  { "a", "b", "c" };

a.ForEach(
     v => { Console.WriteLine(v); } // Lambda Statment
);

JavaScript
var a = [ "a", "b", "c" ];

a.forEach(
    function(v){
        print(v);
    }
);

Data Structures

JavaScript Array can be used as

With Extension Methods we can create the C# methods that we are used to.

Functional Programming

Lambda Expression vs Function

C#
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var evenNumbers = numbers.FindAll(i => i % 2 == 0); // Lambda Expression

evenNumbers.ForEach(n => {  // Lambda Statment
    Console.WriteLine(n); 
});


JavaScript
var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];

var evenNumbers = numbers.filter(function(i) { return i % 2 == 0; });

evenNumbers.forEach(function(n){
    print(n);
});

LINQ, Lambda Expression And A List Of Custom Object

C#
public class Program {    
    static void Main(){
        var annoyingPeopleInHighSchool = new List<Person>() {
            new Person("Descartes", "Rene"        ),
            new Person("Pascal"   , "Baise"       ),
            new Person("Laplace"  , "Pierre-Simon")
        };
        var funnyPeopleInHighSchool = from p in annoyingPeopleInHighSchool
            where p.LastName=="Laplace"
            select p;
        foreach(var p in funnyPeopleInHighSchool)
            Console.WriteLine(p.LastName);
    }
}



JavaScript
var annoyingPeopleInHighSchool = [
    new Person("Descartes", "Rene"        ),
    new Person("Pascal"   , "Baise"       ),
    new Person("Laplace"  , "Pierre-Simon")
];
var funnyPeopleInHighSchool = annoyingPeopleInHighSchool.filter(function(p) {
    return p.LastName==="Laplace" ? p : undefined;
});
funnyPeopleInHighSchool.forEach(function(p){
    print(p.LastName);
});

JavaScript and Visual Studio 2010

Visual Studio 2010 supports

Download the jScript Extension(s) for VS 2010.

function isNullOrUndefined(v) {
    ///	<summary>
    /// Returns true if v is null or undefined 
    ///	</summary>
    ///	<param name="v" type="">The value to test</param>
    return (v === null) || (typeof v == "undefined"); 
}

/// <reference name="chaka.lib.js"/>
/// <reference path="chaka.lib.js"  />

Conclusion

JavaScript

Questions

- ?