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 »
10,640 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 »
66 Comments

As always, very well and concisely done, sir.


Apr 2, 2009 at 11:17 AM // reply »
10,640 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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 12, 2012 at 3:37 AM
Learning ColdFusion 8: CFImage Part III - Watermarks And Transparency
Hi Ben, Just to ask currently it is placed bottom right corner, if i need to replace the same rendered image on the bottom left side or in the bottom center, how that can be calculated. bottom ce ... read »
Feb 11, 2012 at 9:29 PM
Use jQuery's SlideDown() With Fixed-Width Elements To Prevent Jumping
I can't say how glad I am that I found your post. Thank you very much. ... read »
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »