Exploring Mixins And Javascript Objects

Posted April 2, 2009 at 9:50 AM by Ben Nadel

Tags: Javascript / DHTML

After my in-depth exploration of ColdFusion mixin behavior, Rick Osborne asked me how this would compare to mixin behavior in Javascript. I think Rick just likes making my head hurt, but it was an interesting question so I thought I would explore it. It's actually especially interesting because Javascript has both object binding and lexical binding. By that, I mean that Javascript functions can be used in objects, but they also have access to the parent scope in which they were defined (see my graphical explanation of closures). Seeing how this works in the context of method mixins would certainly be interesting.

The code for this test is actually quite short, so I'll show it first then explain it:

  • <script type="text/javascript">
  •  
  • // Run the following code in its own private bubble.
  • (function(){
  •  
  • var strDate = "Thursday, 4/2";
  •  
  • // Define method outside of object.
  • window.PublicFunction = function(){
  • document.write( strDate + "<br />" );
  • document.write( "I am a public function<br />" );
  • }
  •  
  • // Define method outside of object.
  • window.PublicFunctionWithThis = function (){
  • document.write( strDate + "<br />" );
  • document.write( this.Name + "<br />" );
  • }
  •  
  • })();
  •  
  •  
  • // ------------------------------------------------- //
  • // ------------------------------------------------- //
  •  
  •  
  • // Define our test object.
  • function Mixin( strName ){
  • this.Name = strName;
  • }
  •  
  • // Create an instance of our object.
  • var objMixin = new Mixin( "Molly" );
  •  
  • // Bind the simple alert function and execute.
  • objMixin.PublicFunction = PublicFunction;
  • objMixin.PublicFunction();
  •  
  • // Bind the THIS-reference alert function and execute.
  • objMixin.PublicFunction = PublicFunctionWithThis;
  • objMixin.PublicFunction();
  •  
  • </script>

In the first part of the code, I define a function and then immediately execute it within it's own private bubble (function context). By doing this, I ensure that the variable "strDate" is not available to the global scope (window). Then, I define my two methods. They both reference the strDate variable; as seen in my closure demonstration, they will both have access to this variable (lexical binding). The second one, however, alerts "this.Name", a variable which is, at this time, undefined.

Then, I create an object with a "Name" property (remember the this.Name from above). Then, I mixin these two methods and execute them. This is the output we get:

Thursday, 4/2
I am a public function

Thursday, 4/2
Molly

This is very cool! The methods use both runtime and "compile" time binding. The first method really isn't that interesting; but, the second method, PublicFunctionWithThis(), is fascinating. On one hand, it is able to reference the "strDate" variable from its compile-time context, and on the other hand, it is able to access this.Name from its run time, object binding. It get's the best of both worlds!




Reader Comments

Apr 2, 2009 at 10:15 AM // reply »
47 Comments

Very nice Ben, this will definitely come in handy!


Apr 2, 2009 at 10:20 AM // reply »
29 Comments

I liked that you explicitly bound the variables to the global "window" object. The best practice is to explicitly define local variables with 'var' and global variables as 'window.foo'.

You could theoretically leave off the 'var' to implicitly set a global variable. But this entails a performance hit, as the JS interpreter has to search the entire scope chain for the variable. It also leaves you open to exciting bugs if a later code change defines a 'foo' variable somewhere in the scope chain between your function and the global scope.

The main drawback of this approach is that the code is less easily reusable outside the context of a browser. In other JS environments (such as Mozilla Rhino) there is no global window object. This drawback is easily ignored for most developers, but it's useful to know.


Apr 2, 2009 at 10:23 AM // reply »
11,241 Comments

@David,

I actually picked that up looking through the jQuery library code :)

I guess you could get around the window scope issue in Rhino by passing in the global scope:

(function( window ){ .... })( window );

... like how they pass jQuery in and bind it to the $. Unless "window" is an illegal variable name.


Apr 2, 2009 at 10:59 AM // reply »
67 Comments

As always, very well and concisely done, sir.


Apr 2, 2009 at 11:17 AM // reply »
11,241 Comments

@Rick,

Thanks you good sir.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 22, 2013 at 7:52 AM
Nested Views, Routing, And Deep Linking With AngularJS
Hi, Just a quick thank you. As it happens, for my own purposes, the pending ui-router work being done in native angular is likely the one I'll adopt, but your exploration, code and documentation of ... read »
May 22, 2013 at 4:43 AM
How Do You Use The ColdFusion CFParam Tag?
'<cfparam>' or 'isDefined()and <cfset>' performs the same task.Is there any difference? ... read »
May 21, 2013 at 7:46 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
No luck. At least I have uncovered the cause, URLScan 3.1. Here is what I see in the IIS log when a file is over 30mb. 2013-05-21 23:29:05 10.105.45.128 GET /plupload/assets/jquery/jquery-1.8. ... read »
May 21, 2013 at 6:12 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
Ben, I did not see you after Pete Freitag's Lockdown session at cfObjective but he said that IIS sets file size limits at 30MB by default which just happened to be the threshold for file size when ... read »
May 21, 2013 at 11:51 AM
Ask Ben: Parsing Very Large XML Documents In ColdFusion
Looking at my first ever XML document that I have to parse and put into MS SQL 2000 with CF8. I get it to list the desired Field name, many times over, and have a long list of this field name displa ... read »
May 21, 2013 at 9:25 AM
Turning Off and On Identity Column in SQL Server
you are awesome..i am lucky to get this blog between such a garbage one....Thanks, Prashant ... read »
May 20, 2013 at 4:38 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Dana, Your confusion is well founded, since this is a very confusing features. In fact, it ONLY works if you use array notation. Meaning, that this: arrayToList( query[ "columnName" ] ) ... read »
May 20, 2013 at 4:34 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
I was thinking chicken and the egg, I wouldn't have expected it to work in the valuelist going in I guess. Maybe I just need a beer, long day :) ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools