Jeremy D. Miller -- The Shade Tree Developer

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
"Extension Method" in JavaScript

I have to admit a secret.  I actually like JavaScript as a programming language -- especially now with jQuery and QUnit.  It's more out of nostalgia for my earlier programming days doing DHTML applications than the fact that JavaScript is now chic in some circles.  

This morning I found myself wanting some sort of method to check whether an Array object contained a value.  I could have written the code inline, but it was cleaner to just add a new method to the Array class.  Using the prototype object, I'll just add a method called "contains(value)" to all instances of Array:

 Array.prototype.contains = function(value){

     for (var i = 0; i < this.length; i++){

         if (thisIdea == value) return true;

     }

 

     return false;

 }

In the middle of my code it's used like (actions is an array of all the available context menu actions for a row in a table):

 function showMenuItem(actions, item){

     if (actions.contains(item.id)){

         $(item).show();

     }

     else{

         $(item).hide();

     }

 }

 

I'm sure there's a better way to do what I did above, but dang that was easy.  Yeah, C# has extension methods, but JavaScript had open classes first with fewer restrictions than the C# version.


Posted 09-08-2008 7:41 AM by Jeremy D. Miller

[Advertisement]

Comments

julian jelfs wrote re: "Extension Method" in JavaScript
on 09-08-2008 8:47 AM

the important difference is that in c# there is no performance penalty as it is just translated into a static method call by the compiler for you. In javascript every array object you subsequently create will have that extension whether it is used or not. I think this is why you are advised to be careful about extending the prototype of basic types in javascript.  I think it's OK if it is a function that actually makes sense for all Array objects (such as your example) but it can be easily abused (what can't?)

Adrian wrote re: "Extension Method" in JavaScript
on 09-08-2008 9:07 AM

The bizarre bit is that JScript doesen't have contains() built in....oh well its only 2008.....

Jeremy D. Miller wrote re: "Extension Method" in JavaScript
on 09-08-2008 9:28 AM

@Adrian,

That's what I thought too.

Stu wrote re: "Extension Method" in JavaScript
on 09-08-2008 9:33 AM

@julian Since the method was defined on the prototype, I believe the implementation is shared between Array instances, rather than copied as you suggest.

Jeremy, my favourite JS feature is the ability to use map, filter and reduce on arrays.  Nice to be able use functional paradigms and also, a great way to optimise js file size too.

Neil Mosafi wrote re: "Extension Method" in JavaScript
on 09-08-2008 9:51 AM

Actually there is Array.indexOf() which you can use - but it's still not supported in all browsers!

Elijah Manor wrote re: "Extension Method" in JavaScript
on 09-08-2008 10:21 AM

What does the light bulb indicate in your code snippet?

corcoranp wrote re: "Extension Method" in JavaScript
on 09-08-2008 10:53 AM

It is an emoticon representation of '( i )'

Jeremy D. Miller wrote re: "Extension Method" in JavaScript
on 09-08-2008 11:15 AM

@All,

A colleague told me that there is a jQuery method for this.  Note to self:  always look at jQuery docs first.

Paul Cowan wrote re: "Extension Method" in JavaScript
on 09-08-2008 2:27 PM

Why not use the extend function of JQuery:

jQuery.fn.extend({

 check: function() {

   return this.each(function() { this.checked = true; });

 },

 uncheck: function() {

   return this.each(function() { this.checked = false; });

 }

});

$("input[@type=checkbox]").check();

$("input[@type=radio]").uncheck();

Jeremy D. Miller wrote re: "Extension Method" in JavaScript
on 09-08-2008 2:36 PM

@Paul,

Because despite the usefulness and inevitability of such, I think that nested javascript functions are worth avoiding.

Besides, the "prototype" way demonstrated the concept a bit more IMO.

Eber Irigoyen wrote re: "Extension Method" in JavaScript
on 09-08-2008 3:03 PM

and why are we comparing javascript/C# again?

Paul Cowan wrote re: "Extension Method" in JavaScript
on 09-08-2008 4:33 PM

@Jeremy,

Why are nested javascript functions to be avoided?

The functions in question are added to all JQuery objects which might be much more useful.

Jeremy D. Miller wrote re: "Extension Method" in JavaScript
on 09-08-2008 4:47 PM

@Paul,

I think they're hard to read, that's all.  I use them, I just don't like to.

Scott wrote re: "Extension Method" in JavaScript
on 09-08-2008 10:03 PM

Did somebody say ruby?  No?  Oh, then I'll say it.  :)

Really though, open classes that allow monkey patching are awesome as hell, but can also be dangerous in the wrong hands.  Just don't let yourself be the wrong hands.

joey wrote re: "Extension Method" in JavaScript
on 09-09-2008 6:59 AM

take what you know about c# and throw it out the window.

javascript != c#.  different programming style.  nested functions are everywhere.  closures are fun and useful (see module pattern, private member variables, loops and creating event handlers on dom elements).

@Scott

JavaScript has been around as long as Ruby ... so not sure what you are getting at.

@Jeremy

Spend some serious time in JavaScript and you will see the true power of JavaScript.  Most people can't because they lose their intellisense or simply don't understand JavaScript.

Dew Drop - September 9, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - September 9, 2008 | Alvin Ashcraft's Morning Dew
on 09-09-2008 8:42 AM

Pingback from  Dew Drop - September 9, 2008 | Alvin Ashcraft's Morning Dew

Matthew Podwysocki's Blog wrote Object Oriented F# - Extension Everything
on 09-09-2008 6:27 PM

A post by Jeremy Miller caught my eye this morning in regards to extension methods in Javascript . While

Si wrote re: "Extension Method" in JavaScript
on 09-10-2008 6:38 AM

You should probably avoid modifying the prototype of system objects, here's why (run it in the firebug console for best results):

Array.prototype.contains = function(value){

    for (var i = 0; i < this.length; i++){

        if (this[ i] == value) return true;

    }

    return false;

};

var r = ['p','q'];

for(var i in r) {

   console.log(i);

}

Neil Mosafi wrote re: "Extension Method" in JavaScript
on 09-10-2008 12:47 PM

@Si - Great point dude, I had no idea that would happen!!

Dan F wrote re: "Extension Method" in JavaScript
on 09-10-2008 9:33 PM

@Si - don't loop your arrays that way and the problem goes away - www.prototypejs.org/.../array

@julian - Nope, they're shared amongst all instances - see the comments about the respondTo method msdn.microsoft.com/.../cc163419.aspx

@Jeremy - Javascript is wonderful :-)

Object Oriented F# - Extension Everything - taccato! trend tracker, cool hunting, new business ideas wrote Object Oriented F# - Extension Everything - taccato! trend tracker, cool hunting, new business ideas
on 09-10-2008 10:15 PM

Pingback from  Object Oriented F# - Extension Everything - taccato! trend tracker, cool hunting, new business ideas

Michael Schall wrote re: "Extension Method" in JavaScript
on 09-12-2008 5:48 PM

Modifying systems objects will bite you.  What happens when the next version of JavaScript (EcmaScript)  or a browser implementation has a 'contains' function with a different signature?  Or another library you are using modifies the prototype differently?  I want my code to be as future proof as possible.  Not polluting the system objects or global namespace is the safest way to code.  I use the Dojo Toolkit which follows the no pollution rule.  

Here is a library comparison:

dojotoolkit.org/.../why-dojo

Object Oriented F# - Extension Everything - taccato! trend tracker, cool hunting, new business ideas wrote Object Oriented F# - Extension Everything - taccato! trend tracker, cool hunting, new business ideas
on 09-13-2008 8:50 PM

Pingback from  Object Oriented F# - Extension Everything - taccato! trend tracker, cool hunting, new business ideas

ZaM wrote re: "Extension Method" in JavaScript
on 09-14-2008 3:51 PM

Monkey patch!

Alexander Byndyu wrote re: "Extension Method" in JavaScript
on 10-15-2008 2:04 AM

It is very good feature for JS!

I like to use it for custom Array list.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?