ict.ken.be

Delivering solid user friendly software solutions since the dawn of time.

Javascript for C# developers - Notes

Categories: Javascript Notes

Javascript for C# developers
Shawn Wildermuth

 
I am convinced that with the upcoming of all those hybrid application platforms, more and more developers will need to know more and more javascript and related framework. People want to have responsive designs with local storage and prefer to have one code base instead of one for each platform they deploy on. With the release of Node.js people even start to write javascript on server side. Not so sure if that is a good idea, but for sure over time people will prefer to be comfortable with one language instead of the slight speed difference. 
This course by Shawn is short and since you can speed up the video at least at 2x, it will take you less then an hour to watch. It will give you a quick look into the loose typed javascript. Something most of us back-end developers are not so comfy with. Feel free to start using typescript or coffeescript to ease the pain. 

1. Javascript basics

Engines (depends on brower)
  • V8 in Chrome
  • Chakra in IE
  • Monkey in Firefox
 
JIT'ing is based on what browser you're running in.
 
 
Types are typically defined by structure not by identity
var x = 0;
var isNumber = typeof x == "number";
x = new Object(); //no problem, redefines x with new type
http://www.jslint.com/ - can do some type checks for you
 
Classic duck typing
function Feed(ani) { ani.Feed(); } 
function Move(object) { object.Move(); }
Dynamic Typing
var x = {
name: "Shawn",
city: "Atlanta"
};
x.phone = "404-123-1234";
x.makeCall = function () {
callSomeone(this.phone);
};
Global Scope
  • Objects at root are 'global'
 
Closures
  • References outside of function are accessible in function, regardless of lifetime
 
Type Coalescing
"test " + "me" //test me
"test " + 1 //test 1
"test " + true //test true
"test " + (1==1) //test true
100 + "25" //10025
 
1 == "1"; //true
1 === "1"; //false - equality without coalescing
1 !== "1"; //true 
Value Types: boolean, string, number 
if ("hello") {} //true
if ("") {} //false
if (25) {} //true
if (0) {} //false
if (10/0) {} //false (NaN)
var a = null; if (a) {} //false
var u = "One" + "Two";
var single = u[4]; //'T'
log(u.length); //6
  • The number type holds IEEE-754 format which is prone to rounding errors.
var c = 080; //octal starting with zero
var d = 0xffff; //hex
var e = 1.34e6;
 
Number.MIN_VALUE;
Number.MAX_VALUE;
Number.POSITIVE_INFINITY;
Number.NEGATIVE_INFINITY;
 
var fail = 10/0; // NaN
var test1 = NaN == NaN; //false
var test2 = isNaN(NaN); //true
Reference Type: object 
var more = {
"moniker": 1,
height: 4.3,
subData {
option: true,
flavor: "vanilla"
}
}
var a = [ "hello", "goodbye" ];
a.length;
a.push({}); //add to end
var obj = a.pop(); //remove from end
a.shift(); //remove from beginning
a.unshift({}); //add to beginning
var where = c.indexOf(obj);
where = c.lastIndexOf(obj);
//etc. slice, splice, concat
Delegate Type: function
  • Data type much like Func<>
 
Special Type: undefined, null, NaN
var a = null; // "null"
var b = c; // "undefined" 
2. Functions
function foo(one, two, three) {
alert(one);
if (two) alert(two);
if (three) alert(three);
}
  • However there is no overloading, the last definition will override the previous.
  • The arguments.length is available inside function body.
  • Declared parameters do not matter. (arguments[x])
  • All functions return a value, it will return undefined if non existing.
var log = function(s) { alert("yes"); }
function log(s) { alert("yes"); }
var x = log.length; //1 paramter
var y = log.name; //"log"
var z = log.toString(); //"function log(s) { alert("yes"); }"
  • "this" applies to the owner of the function
var f = function() { alert(this); };
f(); // [Object Window]
  • bind() lets you change the owner (context)
var f = obj.myFunc.bind(this); 
f(); //this == global object
Functions define scope
var a = "Hello";
if (true) { var b = a; }
var c = b; //this works
var a = "Hello";
function () { var b = a; }
var c = b; //this doesn't work
  • Anonymous self-executing function protects the global namespace by function scope
  • Javascript lacks real namespaces!
(function(ns) {
var currentDate = new Date();
ns.currentTime = function (){
return currentDate;
};
})(window.MyNamespace = window.MyNamespace || {});
3. Object Oriented Javascript
var name = cust.name;
var nameAlso = cust["name"];
var company = cust."company name"; //does not work
var company = cust["company name"];
  • Dynamic objects work the same as c# dynamic foo = new ExpandoObject();
  • We can mimic c# class unit of work in javascript.
  • Use capital case for functions that are used as classes.
function Customer(name, company) {
//public
this.company = company;
//private
var mailServer = "mail.google.com";
var _name = name;
this.sendEmail = function (email) { sendMailViaServer(mailServer); };
//only use if really needed
Object.defineProperty(this, "name",{
get: function() { return _name; },
set: function(value) { _name = value; }
});
}
var cust = new Customer("Shawn", "Wilder Minds");
var name = cust.name;
cust.sendEmail("foo@test.foo");
 
//Static members
Customer.mailServerToo = "mail.google.com";
var svr = cust.mailServerToo; //doesn't work
var svr = Customer.mailServerToo;
 
//The prototype object
Customer.prototype.mailServer = "Tralala";
Customer.prototype.send = function (email) { 
var svr = this.maiLServer;
};
 
//Inheritance
var test = a instanceof Animal; //true
Cow.prototype = new Animal("Hay");
var c = new Cow("White");
c.feed(); //defined on a
var test2 = c instanceof Animal; //true
var test3 = c instanceof Cow; //true
  • Abstract class is possible, but better to avoid.
  • Protected is not possible.
  • Interfaces aren't necessary, use duck typing.
 
Enumerating Members (reflection)
for (var prop in cust) {
alert(prop); //name
alert(cust[prop]); //value
}
var has = cust.hasOwnProperty("name");
var isEnum = cust.propertyIsEnumerable("name");
  • Extension Methods: add to existing type's prototype.
4. Practical lessons
  • ECMAScript v5 allows more strictness. 
  • "use strict";
  • for..in returns the indexer not the object like in a c# foreach
svr.send({
to: "someone@somewhere.com",
from: "someone@somewhereelse.com",
body: "hello",
subject: "test",
complete: function(r) { alert("Success: " + r); },
error: function(e) { alert("Failed: " + e); }
});
 
SmtpClient.prototype.send = function(msg) {
var defaults = {
to: "bla@blo.bli"
};
$.extend(defaults, msg); //jQuery
var to = default.to;
};
Architecting large javascript codebases