tags:

views:

91

answers:

4

ok, I was experimenting (getting straight in my head) all this object oriented like stuff javascript can do, and Im simulating inheritance with functions, adding functions to functions (too cool!) and I had a AHA! moment.

var myArray = [function(){console.log("im in an array!");}, 2, "fly feet!"];
myArray[0]();

Of course, now that Ive done it, Ill find its a common thing and useful for somesuch thing... BUT I DISCOVERED IT!!!

Anyone care to share their AHA! moments?

+2  A: 

When I understood the answer to this question:

How exactly does the JavaScript expression [1 [{}]] parse?

Your AHA moment is an example of first-class functions.

Jesse Dhillon
I realized thats what it was, that was the specific thing I was (have been) studying. I'd never seen it done in an array, had to try it, was all happy it worked!
jason
+1  A: 

I don't think I had an AHA moment. After learning that everything most things in JavaScript are objects, I realized that something like this is possible:

console.log("I'm not wearing pants".replace('not ', ''))
// Produces: "I'm wearing pants"

As is this:

foo = function(operation) {
  operation();
}

pants = function() {
  console.log("I'm not wearing pants!!");
}

foo(pants); // Produces console output of "I'm not wearing pants!!"
Hooray Im Helping
Not *everything* in JavaScript is an object, there are *primitive values* such string, number, boolean, undefined, and null *values*. There are also primitive value wrapper objects, for string, number and boolean values, e.g.: `typeof "" == "string"; // primitive` vs `typeof new String("") == "object"; // primitive wrapper`
CMS
whoa... very cool. That seems very close to how eval works.
jason
+1  A: 

Since functions are first-class objects in JavaScript, you can use them anywhere you would use an object, that includes storing them in an array or even doing things like returning a function from another function.

function one() {
    alert("one");
    function two() {
        alert("two");
    }
    return two;
}

one()();
fms
Whats happening with the ()(); ? edit NM I figured it out. One() evaluates to two, which gets the other () slapped on it. Badass.
jason