Friday, September 21st, 2007

Finding ‘send’ in JavaScript

Category: JavaScript, Tip

Ola Bini found send in JavaScript and it was a surprise for a bunch of people.

To call a method on a function you use (). You could get the function object via the ‘.’ notation, or the array access method. This is why it makes sense that given:

javascript

  1. window.foo = function() {
  2.   alert('in the foo function');
  3. };

The following are the same:

javascript

  1. window.foo();
  2.  
  3. window['foo']();

Or if you are Ola:

javascript

  1. function SendTester() {}
  2. SendTester.prototype.foo = function() {
  3.    alert("Hello");
  4. };
  5.  
  6. new SendTester().foo();
  7. var name = 'foo';
  8. new SendTester()[name]();

Posted by Dion Almaer at 1:18 am
37 Comments

++---
2.2 rating from 59 votes

37 Comments »

Comments feed TrackBack URI

No, I can’t say it’s a great discovery, but I know many experienced web developers who would be surprised to find this as well. The “advanced” features of Javascript still aren’t very well-known. Closures, the module pattern, etc. are mostly known through their Prototype/jQuery use, but fundamental knowledge of Javascript is often lacking.

Comment by sb — September 21, 2007

I don’t get it.

a.b === a[‘b’]

Isn’t that like basic JavaScript 101?

Comment by Michael Geary — September 21, 2007

@Michael

You’ll be surprised. I only figured that out like half a year ago and I’ve doing JS for uhmm… years.

Unfortunately, the eval function truly is evil, because you can just do:

eval(“a.” + b) instead of a[b]

… so some people never end up learning, because they’re not forced to.

Comment by Marat Denenberg — September 21, 2007

So what’s new in it? This is standard feature of language. If you want you can even write code like this:
a()[name]()()(2).method()
Please read reference and/or guides and, of course, look inside sources of good libraries. And then, if you find out something you haven’t seen anywhere, post it here.

Comment by emil — September 21, 2007

Emil: People definitively won’t be post anything they find here, if the response they’ll get is So what’s new in it?”.

The post was a simple “Damn, I didn’t know I could do this!”. There’s no need for all to brag about knowing about it first. Everyone in the world who knew about it is in the same category. The important part is that now one more person does and, as an insight, there’s a lot of people out there that have learn JS on their own and don’t know a lot about it yet (because they haven’t needed to or because they haven’t had any formal training).

This happens of all languages, too. It depends a lot on how you learn about them or who teaches them to you.

Now, we can assume you all smart people already knew about this before Ola. No need to clarify it.

Comment by eduo — September 21, 2007

Interesting – but I think experienced JS coders would use this automatically if they needed to access a property with variable (varying) name, and that property was a [pointer to] function.. Never hurts to repeat though.
Anyway – (offtopic) – at first when I saw an extract of this article in my RSS reader, I thought it was about how easy is to learn JavaScript for rookies, and then thought that if the JS2 spec gets implemented and into mainstream (and it looks like it will, see Tamarin), then the current JS with its cross-browser problems will become an object of our nostalgy. IMO, they make a C++ (not even Java) out of JS. This was published here on Ajaxian in march ( ajaxian.com/archives/participating-or-observing-ecmascript-4 ), but nobody responded, and the specs wiki discussion doesn’t allow for writing or even viewing. Somehow I think something isn’t right here. I mean, we should care more about these things.

Comment by ypct — September 21, 2007

wow, you opened my eyes. I think you would be also surprised that you can do even this:
var a = null;
var b = function(){alert(‘hello’);}
(a||b)();
or that … (more samples)

damn, just read at least one good book about language you are going to use, don’t make a sensations from base things that everybody should know. Don’t make lame blog from ajaxian, leave it for good and interesting announcements, go to some jsfornewbies.com site

Comment by anonymous — September 21, 2007

We can all say “I knew that for N years”, “that’s nothing, I’ve known that for N + k years”, but the fact is that there are people out there who simply don’t know. From my experience, even very experienced Javascript developers hardly know anything about the basics of Javascript. They simply know the parts that look like other languages, and use those. In my opinion, that’s what this post is about. Web developers often have their own methods to achieve just about anything, but spend too little time figuring out how to actually do it right.

Comment by sb — September 21, 2007

Eduo:
Nothing personal. I just have seen too many lists or pages that turns into “how can I attach an event to element” ones. There’s enough good articles out there to learn language basics and this *is* pretty basic thing. I like this page because articles here assumes I know language at some, rather more than basic, level. But, huh, I won’t write more, flame war is a bit stupid thing.

Comment by emil — September 21, 2007

anonymous: I think you have 2 errors in your JavaScript – try to run it in Mozilla. You used bad type of quotes for String literal and your last expression throws an error. Howerver

var c = a || b;
c();

works. (Wich I didn’t know either!)
The point is, that it’s always good to have this sort of articles and discussions, and it certainly doesn’t make Ajaxian lame.

Comment by ypct — September 21, 2007

I agree with Emil the majority of javascript ‘coders’ end up copying and pasteing because there isn’t may good sites explaining with good examples. This copying only leads to more broken pages that only work in one browser :(

Comment by pete — September 21, 2007

In defense of post value — I know one practical application of the the “array access method” described.

If you are scripting ActiveX/NPlugin control with J(ava)Script, and some of its methods have names that conflict with JS keyword, then you forced to use “associative array access” notation. This happens to me with Microsoft Office Web Controls, where a lot of objects has “delete” method, so you forced to use:

xlRange[“delete”]();

VS

Comment by Valery Silaev — September 21, 2007

LOL I agree this 101 stuff

Comment by John Giotta — September 21, 2007

eduo, sb — apparently you’re new here. Here in the Ajaxian comments, it is your responsibility to deride every “proof of concept” application, neat trick, and simple discovery.

Some people have very fragile egos, and they need every opportunity they can get to help themselves feel better. ;)

Comment by mdm-adph — September 21, 2007

Yeah I’m wondering why there’s a post on Ajaxian stating the obvious :-/

Comment by Rory — September 21, 2007

Ease up. People of all skill levels come to this site. It isn’t just for uber-coders.

Comment by James MacFarlane — September 21, 2007

You guys make me look nice today :)

Comment by Dan — September 21, 2007

I had a similar moment of a-ha! a few months back:

http://rethink.unspace.ca/2007/6/13/javascript-is-not-widely-understood

I’m so glad that Ajaxian isn’t just announcements of new versions of Google Gears, personally. We’re all in this together, and nobody except Alex Russell or John Resig can likely claim to keep every nuance of the language in their heads at once. I say, keep the discoveries coming.. I guarantee that lots of people will learn from this post.

Comment by Pete Forde — September 21, 2007

There are many undocumented things in JavaScript and CSS like this! But I don’t really know this one before, thanks!

Comment by chenggn — September 21, 2007

Wow! didn’t know ajaxian.com was frequented by such smart people that know every single feature and trick about JS (maybe everything in the world) that find this article useless and an insult to their fabulous minds…

Bini must be a little bit retarded (just like me) to find this article interesting, whats next? JRuby? lol, what a stupid guy….

Comment by Pedro — September 21, 2007

The reason that this is an interesting discovery for many (I know I just discovered it myself a few weeks ago) is that while javascript has a C/Java-like syntax, and many approach it from C /C++/C#/Java backgrounds, javascript is more expressive than those languages in many ways.

As for “reading a manual”, that’s a pretty sad and ineffective way to learn a language, for me at least. I find the only way for me to really appreciate a dimension of expressiveness in a language is for me to need and use it in a practical situation.

Ola needed “send” and that taught him about functions as objects, objects as hashtables, and “(” as a function invokation operator.

Comment by K9 — September 21, 2007

Oops filled in the form wrong, i don’t actually own K9.com…

Comment by K9 — September 21, 2007

document.getElementsByTagName(“head”)[0]

({false:function(w){alert(w)},true:function(){return this}})[‘b’ in {‘a’:1,’b’:1}]()[!1](“it’s just JavaScript”)

Comment by Andrea Giammarchi — September 21, 2007

I’m happy to see that, finally, developers are “discovering” that javascript is actually a wonderfully powerful language. Yes, this is 101 in terms of theory, but the point (for me) is this: the powerful OO architecture of JS allows nested subclasses, accessible if necessary via “arrays”, and it doesn’t take much to see how this kind of thing makes for a nicely encapsulated and well organized system. As “web applications” are strange in that they mix brute stringish stuff like html and form data with programming languages — the reason that eval() continues, unfortunately — I hope that more people build using these techniques, instead of the rather ubiquitous silly javascript that spawns from lack of knowledge. This post hopefully has slapped a few brains into awareness.

Comment by jimbob — September 21, 2007

Now if only he could find the equivalent of method_missing …..

Comment by beppu — September 21, 2007

What we still need is getter and setter to be supported in all browser

Comment by Georg Miller — September 21, 2007

Next up: The basic arithmetic operators! All four of them! Plus bonus chapter on overriding precedence with parens! All secrets revealed!

I am so glad ajaxian follows the cutting edge.

Comment by Martin — September 21, 2007

“Ola needed ‘send’ and that taught him about functions as objects, objects as hashtables, and ‘(‘ as a function invokation operator.”

Indeed, and I think it’s great that people are blogging about their experiences in learning JavaScript.

But is it really the mission of Ajaxian to chronicle people’s discoveries of things like “you can use parentheses to call a function” and “object[‘name’] is the same as object.name”?

If it is, so be it. I’m not an Ajaxian, and it’s their blog and their choice of content. It just seems a bit like running an article on the difference between while(){} and do{}while().

Comment by Michael Geary — September 21, 2007

I found a great approach:
i = i + 1 can be rewritten as i++ .
Cool!

Comment by Tio Malandra — September 22, 2007

While this may be obvious to the more experienced developers, who perhaps are the biggest group of Ajaxian-visitors, it is not that obvious for people like myself: beginners, guys/girls struggling to get to grips with JS.
Saying this is basic JS knowledge (which it might be, I don’t know) is one thing; making Ola’s “discovery” ridiculous is another.

Comment by Max Steenbergen — September 22, 2007

I didn’t know you can do this. Thanx for posting =)

Comment by andrija — September 23, 2007

Noone is making fun of Ola. The ridicule is aimed at the Ajaxian editor.

Comment by Martin — September 23, 2007

It does seem there are a growing number of poorly researched articles showing up on Ajaxian. I would suggest that if you are to maintain credibility in the community that posts like this need to show that some research was done on the topic. With an opener like “Ola Bini found send in JavaScript” there is an implication that nobody documented this before.

If Ajaxian stepped up and did some homework, like many of the commentators, posting links to other sites that cover the same material, then there would be less hostility. I do not think the issue is so much with what some see as basic knowledge as it is with the presentation of that knowledge being “found” by a single source. The article ‘A Cheaky Way to Style an input type=”file”’ suffered from the same lack of research and implied “discovery”.

This site has become a resource for many, and the expectations are higher than of an individual’s blog. A few minutes with a search engine, saving the readers from doing it themselves, would be greatly appreciated.

Comment by Wade Harrell — September 24, 2007

Tio, i=i+1 is not equivalent to i++. It’s equivalent to ++i, and there’s a difference there. I guess you’re still learning javascript too?

Michael, the difference between “while” and “do…while” is insignificant and purely about convenience, whereas “send” relies on more important features of javascript.

Comment by K9 — September 24, 2007

Well since these comments keep going on and as they do so get into the more basics of coding it’s not quite true that “the difference between “while” and “do…while” is insignificant and purely about convenience”. A do/while loop is intended for AT LEAST ONE iteration whereas a while loop MAY NOT HAVE ANY ( 0 or more) iterations.

Comment by mxt — September 24, 2007

Absolutely right mxt, but my point is that if you just had “while” or just had “do…while” you could make up for the lack of the other in a couple seconds. On the other hand, javascript’s ability to do “send” is a more significant language feature. So having a post about “do…while” would indeed be silly, whereas a post about “send” is a post about the power of javascript.

Comment by K9 — September 24, 2007

Well, I must say to be very disappointed in the social intelligence some of the commenters have displayed here…
Not all people reading this blog actually program professionally in javascript. People who do other things might just be interested in javascript and related technologies and not have all the insights a pro can have in this area.
Posts like this can invite the non-godly javascript programmers into reading this blog and gain interest in javascript.
I find Ajaxian the best javascript blog around and I don’t mind occasionally seeing posts like this one. I see it more as a good reminder of what a liberal language Javascript is.

Comment by R2D2 — September 26, 2007

Leave a comment

You must be logged in to post a comment.