Skip to content


Experiment: Ruby-style function auto-calling in Javascript

I have no clue what it’s called when ruby automatically runs a function.
After not totally understanding def.js and looking at this coffee-script issue from the cappuccino github issues browser. I had a horrible idea.

Function.prototype.valueOf = function(){return this()}

What does it do?

function getValue(){
return 42
}
if(getValue == 42){
alert('fortytwo')
}else{
alert('not fortytwo')
}

Notice notably absent in the if statement are the expected parentheses ‘()’ needed to call them. It gets stranger still.

alert(getValue == 42); //true
alert(getValue() == 42); //true
alert(getValue() === 42); //true
alert(getValue === 42); //false
typeof getValue() //number
typeof getValue //function

var sample1 = getValue;
typeof(sample1) //function

var sample2 = getValue();
typeof(sample2) //number

One advantage is that it makes a super hacky/semi-working implementation of getters that should work universally (maybe). Except that it doesn’t. It’s practically useless.

Posted in Uncategorized.

Tagged with , , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.