While that may be true, it's a mistake to assume that the saccharine in the syntax is dependent on a language's dynamic typing. This point is amply demonstrated for those who've been keeping up with the development of C#, a static language whose syntax is sufficiently honeyed that the below snippet is remarkably comparable to the Javascript version after it. I tried to match up the code as much as possible to make the comparison easier.
C#
public class myClass
{
public string myProp { get; set; }
static void Main(string[] args)
{
var myc = new myClass() { myProp = "English" };
myc.manhandleStr();
System.Console.Out.WriteLine(myc.myProp);
}
}
public static class ExtMethodClass
{
public static void manhandleStr(this myClass cl)
{
var palaver = new
{
myName = "Nym",
myTaskList = new List<Action<string>>
{
next => { cl.myProp = next + ".com"; },
next => { cl.myProp =
next.Replace("l","r").ToLower(); }
}
};
palaver.myTaskList.ForEach(task => task(cl.myProp));
}
}
Javascript
var myc =
{
myProp: "English"
};
myc.manhandleStr = function() {
var palaver =
{
myName: "Nym",
myTaskList:
[
function(next) { myc.myProp = next + ".com"; },
function(next) { myc.myProp =
next.replace("l","r").toLowerCase(); }
]
};
palaver.myTaskList.forEach(function(task) { task(myc.myProp); });
}
myc.manhandleStr();
alert(myc.myProp);
By the way, other C# programmers might scold you for writing code like this. And yes, I realize that fundamentally (i.e. semantically rather than superficially) the dynamic Javascript object "myc" differs from the static C# instance "myc". Keep tuned for the "dynamic" keyword that's on the way in C# for duck-typing variables going to and from CLR dynamic languages.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.