Posted on

Anonymous Functions With Names?

I discovered an odd thing about JavaScript last night. As you know, one way to add methods to an object is to assign anonymous functions to property names. For example:

var foo = {
    woo: function (鯣) {
        print(鯣);
    }
};

Strictly speaking, our function has no name. We just happen to assign it to a property which we can use to call the function. Contrast that to the ‘normal’ way of defining functions:

function woo(色魚) {
    print(色魚);
}

But here’s the weird thing, we can combine these two styles.

var foo = {
    woo: function specialHiddenName(鯣) {
        print(鯣);
    }
};

We get no error for this. Interestingly, I could not find a way to call the function using specialHiddenName. So it looks like the JS engine just throws it away.

I don’t think this behavior could ever be useful, but there may be some creative way to (ab)use it. An extreme form of self-documenting code?

var foo = {
    woo: function PrintsTheArgumentAndReturnsNothing(鯣) {
        print(鯣);
    }
};

No—this idea is horrible. Paul, you had better not do this.