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,247 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,247 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 25, 2013 at 10:08 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
@Ben, my question is that i want the current node with its tag and its parent node. i just want only that data. So, give me the solution for that. and remember solution is working on " xpath 1.0 ... read »
May 25, 2013 at 10:01 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
hey ben, i want get my current node tag and also want the root node tag withing. So, how can i fix it.. ! ... read »
May 24, 2013 at 5:39 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Adam Oops! My mistake! I hadn't gotten that far in my testing - I'm still baby stepping my way through the process. ... read »
May 24, 2013 at 5:13 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
Hi Jason, Thanks for checking up on that, but I still stand firm on my position. :) There are actually two listLast()'s in use, and you're right that the one using a space as a delimiter is fine. ... read »
May 24, 2013 at 4:45 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Ben I have been lurking your site for quite some time, and haven't stepped up to comment until today. Thanks for all the great info - keep it up! @Adam I believe you are mistaken... as the commen ... read »
May 24, 2013 at 11:21 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, Ha ha, let's us never speak of justifying "##" notation again :P ... read »
May 24, 2013 at 11:18 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Ah, so it was indeed how I vaguely remembered it to be: A direct assignment value = users.id[ i ] causes value to retain the sticky datatype of the query column. Although unnecessary in ... read »
May 24, 2013 at 9:11 AM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Brandon, Hi, No, I haven't been able to do that. I have just kept it as it is. ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools