After a few days back at work and going over both my notes and the three blogs I wrote about MIX 11 I have have had a chance to create a summary list of links to the ‘best’ presentations and the ‘good’ preview bits. The prior blogs can be found here: [Day One] [Day Two] [Day Three].
On the second day of MIX 11, noted standup comic and all around funny man, Douglas Crockford, brought his act back to Vegas. His routine was supported by fellow Javascript lumniaries: Luke Hoban, Allen Wirfs-Brock and Tomasz Janczuk. Crockford took issue with the W3C’s work on HTML5 for (and we paraphrase) ‘adding features without dealing with the security implications of these features and failing to correct existing security features in the DOM.’ Such comic bits along with his well known ‘Javascript is a near perfect language’ riff bought the crowd of the almost empty auditorium to its feet. The small turn out for this panel is inexplicable to your scribe who attended a standing room only audience of almost 2,000 for a similar panel on Javascript (which included Crockford, Wirfs-Brock, Brendon Eich and Mark Miller) at the great, lamented Ajax Experience Conference in Boston in 2009. The panel is to be complemented also for the extremely well tuned sense of haute couture which they brought to the stage. Douglas Crockford also gave a second presentation coving changes coming in ECMAScript 5
Criminally Irresponsible
A high point of the Microsoft sessions on Day Two was “An Over view of the MS Web Stack of Love” as presented by the always entertaining Scott Hanselman. Walking the high wire with a live demo featuring yesterday’s (!) build of the Visual Studio/Framework 4 MVC Scott presented a lively and very informative overview of MVC 3. The session tape for this session is a much see. Anyone who has any experience with RADRails will enjoy the familiar ‘embrace and extend’ strategy with Microsoft can play so well. This is a monster effort from Microsoft and should grab back some of the mind share which MS lost in the Web community with its soon to be forgotten Web Forms approach. Please have a look at what MS is doing in this area. Insanely great and with an open embrace of the open community support (via NuGet). Entity Framwork which has some what of a confused history at Microsoft has finally found a home in this product. MVC support (via EF) not only code first design (ala RADRails) but Model First and Schema First – dealers choice! That and a little Linq, some JQuery and (soon) HTML5/CSS3 and this product is
Hot, Hot,Hot!
Get the bits, watch the session tape and code.
Scott Wows The Crowd at the Tuesday Keynote.
(See boss I did attend at least some of at least one keynote)
And of course there were the mini sessions in the afternoon:
Microsoft finally got around to posting a list of the sessions available for MIX 2011. There are 86 sessions, keynotes and Boot Camps - with a lot of attention to Phone 7 and a surprising number of Silverlight sessions. Sessions of interest to me: MVC and Azure and HTML5 are well represented. Although there is a fair amount of non-Micro$oft content the weight is still heavy on things which Microsoft can sell you (like Azure cloud services) or products you can code for which will make Microsoft money (Phone 7). But then again Microsoft is a capitalist organization not a social club. Content quality looks to be at the consistently high level of prior conferences. The Java Script panel is well hosted (Crockford, Hoban, Wifs-Brock and Janzcuk) and should be a lot of fun. Now if we could only get John Resig to attend (dream on).
The downside for me (a self admitted code head) is that the sessions are crammed into a pretty small space (6 hours per day of sessions) so even a very dedicated attendee will only be able to attend about 18 sessions. My personal list would include about 30 sessions so unless the actual (as yet unannounced) schedule is magical I am going to have to miss some good stuff. Oh well, I can always check out how to program Phone 7 (this will go well with my knowledge of PL/1. The keynotes are two additional hours each Tuesday and Wednesday mornings. Hopefully these will be available on-line so sleeping in Tuesday and Wednesday will be an option.
Everything in JavaScript is an object. The names are changed to confuse the innocent. JavaScript Object can have “properties” but these are themselves, objects. So a JavaScript object is composed of a list (dictionary) of objects (properties). Some objects hold simple (primitive) values (numbers, strings), some objects hold (are) functions. So let’s begin.
The Basics
var a=new Object();
Create a new, 'empty' object.
a["Alpha"]="Simple String";
Add a property, a 'string' object
a.Alpha="Simple String";
Add a property, alternative, common syntax
a="{Alpha : 'Simple String'};
YAS (Yet another syntax – Introducing Object Literal Syntax)
a.Alpha
returns 'Simple String'
a["Alpha"]
Alternative Syntax, same results
Identifier Issues
You might ask yourself if "Alpha" is an object owned by the object "a"; who owns "a"? Every object exists in the CONTEXT in which it is created. Therefore "a" is a property of its containing context. Since this is raw code we can use the "this" object to identify that context. So we can write:
this["a"]["Alpha"]
this.a.Alpha
Compact, alternative syntax.
There are a couple of issues here. It is possible to create a property name in one syntax which is illegal in the alternative syntax. This is legal
a["0"]=0;
but watch out, the next line is an error:
var b=a.0;
Syntax error. Identifiers cannot begin with a number.
How do we know what objects are associated with an object. How do we know what properties are associated with the dictionary of the master object? To do this we will use a JavaScript intrinsic: typeof. The intrinsic typeof takes an identifier as an argument and returns a string.
var a=new Object();
a["Alpha"]="Simple String";
typeof(a) returns "object"
typeof(a.Alpha) returns "string"
typeof(this.a) returns "object"
typeof(this.a.Alpha) returns "string"
typeof(a.Beta) returns "undefined"
typeof(b) returns "undefined"
typeof(b.x) returns a SYNTAX ERROR
We can avoid this syntax error only by first testing whether the parent exists (typeof(b)!='undefined')
We can package this nested testing into a pair of JavaScript functions:
function IfObject(context,objectName){
if (typeof(context)==='undefined'){
return false;
}
if (typeof(context[objectName])==='undefined'){
return false;
}
return true;
}
function IfPropertyExists(context,objectName,propertyName){
if (!IfObject(context,objectName)){
return false;
}
if (context[objectName][propertyName]=='undefined'){
return false;
}
return true;
}
}
IFPropertyExists(this,"b","x") returns false
And no syntax error!
We can iterate through the objects within a parent object as follows:
var a=new Object();
a["Alpha"]="Simple String";
a["Beta"]='Second String';
for (var propName in a) {
alert("a["+propName+"] equals " + a[propName]);
}
Returns
a["Alpha"] equals Simple String
a["Beta"] equals Second String
Object Literal Notation
Object Literal Notation, whose reigning expert is Douglas Crockford, is also known as JSON (JavaScript Object Notation), is increasingly important in all types of JavaScript programming not least of which is has the preferred method of delivering data payloads using AJAX. We can repeat the discussion above using Object Literal Notation.
var c={Alpha : 'Simple String', Beta : 'Second String'};
c["Alpha"] returns "Simple String"
c.Beta returns "Second String "
Now let's turn it up a notch and add a function as a property object using JSON:
var d={Alpha : 'Simple String', Beta : function(){ return 'Dennis';}};
d.Beta() returns 'Dennis'
d["Beta"]() returns 'Dennis'
If the JSON is stored in a string (think AJAX data package) we can unpack the object using the eval intrinsic.
var objectLiteralString="{Alpha : 'Simple String', Beta : function(){ return 'Dennis';}}";
objectLiteralString now equals the STRING "{Alpha : 'Simple String', Beta : function(){ return 'Dennis';}}"
Wrap the string in parenthesis and call the eval intrinsic to re-hydrate the object
var e=eval("("+objectLiteralString+")");
e.Beta() returns "Dennis"
e["Alpha"] returns "Simple String"
Get it? Good.
EndNote:
We seem to have wandered into the topic of functions here, so let me add an end note on passing objects as parameters. When using an object as a parameter argument the object is passed "by reference". That means that the object pointer cannot be changed but, stay awake here, the properties of the object may be modified and the modification will be 'seen' outside of the function. Let see this by example:
var Gamma={a: "first", b:"second", shout : function(){return 'WOW';}};
Gamma.shout() returns "WOW"
function DogVoice(){return 'Bark';}
This defines a new function object which we want to replace for the shout function property of the object Gamma
function PassByReference(_objectRef,_propertyName,_newFunction){
_objectRef[_propertyName]=_newFunction;
}
Now use the function
PassByReference(Gamma,"shout",DogVoice);
Gamma.shout() returns "Bark"
The shout function has been changed from inside of the external function
We cannot assign a new value to Gamma inside of a function
function DoesNotWork(_objectRef){
_objectRef=null;
}
Define the function and then use it
DoesNotWork(Gamma);
Call the function, assign null to Gamma within the function;
But this will have no effect on the Gamma outside of the function
Here is the current status of the book as listed at the book publishers site:
Table of Contents Resources
1. Introduction – FREE
2: Testing and debugging – AVAILABLE
3: Functions – AVAILABLE
4: Closures – AVAILABLE
5: Function prototypes – AVAILABLE
6: Timers – AVAILABLE
7: Regular expressions – AVAILABLE
8: With statements – AVAILABLE
9: Code evaluation – AVAILABLE
10: Strategies for cross-browser code – AVAILABLE
11: CSS Selector Engine – AVAILABLE
12: DOM modification – AVAILABLE
13: Attributes and CSS
14: Events
15: Ajax
16: Animation
17: Performance
* Author Online
Go here to discuss this title with the author
* Source code (66 KB)
Closures are one of the most powerful features of ECMAScript (JavaScript) but they cannot be property exploited without understanding them. They are, however, relatively easy to create, even accidentally, and their creation has potentially harmful consequences, particularly in some relatively common web browser environments. To avoid accidentally encountering the drawbacks and to take advantage of the benefits they offer it is necessary to understand their mechanism. This depends heavily on the role of scope chains in identifier resolution and so on the resolution of property names on objects.
Most of what we will discuss today is taken from Crockford’s seminal essay on Private Fields And Closure. Please note: The current examples (and those in Crockford’s essay) depend on the use of the JavaScript “new” verb in order to ‘instantiate’ a JavaScript object. Crockford’s more recent work treats “new” as unsafe JavaScript. As such, his JSLint program will flag uses of new with warnings in its ‘strict’ mode. I, personally, don’t have a problem with “new” in JavaScript but we will not go into that debate here. Part III will introduce a non-”new” constructor method anyway.So, let’s begin.
Recall how private methods (aka inner methods) can be defined in an object:
1. function Container(param){
2. return makeSmall(param);
3. function makeSmall(arg){
4. return arg.toLowerCase();
5. }
6. }
7. var out=Container('BIGFISH');
Nothing fancy here. Let’s look at this short code segment as the un-threaded JavaScript inturprature
looks at it.
Read line #1. Create a object called “Container” enclosed by brackets at line #1 and line#6.
Read lines #1 through #6, check for syntax and DO NOT EXECUTE any code.
Create an enclosure within Container called “makeSmall”. Lines #3 through #5
Read line #7, check for syntax and EXECUTE Container(‘BIGFISH’);
Execute line #2. To do so:
Execute the function makeSmall on line #3
Return the results of makeSmall as the results of the call to Container
the var “now” then contains the string ‘bigfish’
“makeSmall” is an inner method of Container ( Often called a private function by Crockford). In addition
to methods we can create private fields within an object with syntax like this:
function Container(param){
var privateField;
}
“privateField” is, like “makeSmall” in the prior example, not visible outside of Container.
Public Methods and Fields At Last: Using “new” in JavaScript
Ok, we are almost there. Here is something that looks
like a class definition (but its not really). The following code is NOT executable by itself.
function Container(param) {
function makeSmall(arg){
return arg.toLowerCase();
}
var member = param;
this.Service = function () {//use of "this" is required here
return member;
}
this.PublicField='Everyone Sees Me, I hope';//use of "this" is required here.
}
In this container we have defined two private objects:
the private function: makeSmall; and
the private field: member; and
we have defined two public objects:
a public function: this.Service
a public field: this.PublicField
To use “Container” object we need to deploy the “new” verb:
var b=new Container2('abc');
alert(b.Service()); //this will return the string 'abc';
Note that Service is public and is defined using JSON syntax: this.Service = function(){…};
Crockfords notes that, defined this way, Service can only reference private members,
and fields within the Container object. We can do better, but we must work a little harder.
Private
fields are static within the derived object (i.e. var x=new Container(…);)
Member
Field
Private
that
Field
Private
Pointer
to the execution context in the Container object was instantiated. This
private field must be used within any private or public function to access
Public Fields and Functions. Note, that “that” must be set during object instantiation
only.
this.Special
Function
Public
This
function accesses only private fields.
This.SpecialService
Function
Public
This function accesses private functions and fields. It also access a public Field (that.PublicField).
Container is a JavaScript object but it can ONLY be used
with a “new” statement:
var myContainer=new Container('FATCAT');
Container is NOT a class definition (no such animal exists in JavaScript). Here is the walk through of code execution during a instantiation.
The object “myContainer” is instantiated as an instance of Container.
Function dec is defined but not executed.
·This.PublicField is defined and set to the lower case of the input parameter.
·member is defined and set to the original value of the input parameter.
·privateField is defined and set to the value of 3.
·“that” is defined and set to “this”. At this execution moment, “this” is equal to a pointer to the execution context where the object “a” is being created. JavaScript does not guarantee that the value of “this” will remain constant during the course of your program execution. Please see the PS at the end of this blog for additional information.
·this.Special is defined and not executed.
·this.SpecialService is defined and not executed.
Ok, so much for this, that and the other thing. In the next post on this subject we will find a syntax to allow us to do away with the “new” verb and still get an object back in return.
PS
One additonal word about using the parttern:
var that=this;
The stratagy of using “that” is required when you need to make internal references to Public properties of the object.
From the above example if we are given:
this.PublicField=param.toLowerCase();
var that=this;
this.SpecialService = function () {
if (dec()) {
return that.PublicField;
} else {
return null;
}
};
the reference to PublicField in:
return that.PublicField;
Requires the use of the that modifier. However references to private (internal) properties explicitly
require NOT using the "that." modifier.
In the current example note how the function "dec" is coded:
function dec() {
if (privateField < 0) {
privateField -= 1;
return true;
} else {
return false;
}
}
“Javascript is the only language people use without first learning the language.”
- Douglas Crockford
Sometimes called the Godfather of Javascript, Douglas Crockford is currently the premier authority on safe, effective Javascript. If you use Javascript and have not seen: Javascript – The Good PartsStop what you are doing and watch this presentation now. This is a great presentation of Crockfords mature thinking on Javascript. After working for years on advanced methods of inheritance in javascript he has moved beyond both Prototypal and Pseudoclassical inheritance. Crockford currently recommends what he calls Parasitic Inheritiance (aka: the Power Constructor). To get into all the details, including some dead ends which Crockford has explored try his presentation: Advanced Javascript.
I will be discussing Crockford’s use of Closures, the Singleton and the Power Constructor in the next few Javascript posts. Until then take a look at these presentations. Your code will never be the same again.