views:

159

answers:

4

The ECMA standard defines a hidden, internal property [[Call]], which, if implemented, mean the object is callable / is a function.

In Python, something similar takes place, except that you can override it yourself to create your own callable objects:

>>> class B:
...     def __call__(self, x,y): print x,y
...
>>> inst = B()
>>> inst(1,2)
1, 2

Is there any similar mechanism available in standard JavaScript? If not, what about any of the current JavaScript implementations?

+1  A: 

As far as I know it's not possible. It is supposed to be an internal property of an object and not exposed to the script itself. The only way I know is to define a function.

However, since functions is first class citizens you can add properties to them:

function myfunc(){
  var myself = arguments.callee;
  myself.anotherfunc();
}

myfunc.avalue=5;

myfunc.anotherfunc=function(){
  alert(this.avalue);
}

myfunc(); //Alerts 5
myfunc.anotherfunc(); //Alerts 5
some
A: 

It is not possible yet: [[Call]] is hidden and not directly available in all conformat implementations. It may change in the new standard of ECMAScript.

Eugene Lazutkin
+1  A: 

[[Call]] is an internal property used to describe a particular piece of functionality in the language specification. There's no guarantee that such a property is even available in an interpreter. There are many other properties and objects that are referenced in the spec, such as the Completion object, which is only necessary if you have implemented the language as an AST interpreter which is what KJS and JavaScriptCore (JSC == WebKit fork of KJS) used to do. Non-AST based interpreters (SpiderMonkey, the new KJS and JavaScriptCore execution engines FrostByte and SquirrelFish, probably the Opera JS engine, and V8) have no need a lot of these constructs as they are used primarily for the purpose of describing behaviour -- not implementation.

There is another reason that such access isn't available -- A lot of these properties are so intrinsic to the interpreter that allowing custom behaviour can impact performance whether those features are used or not -- for instance the JSC API provides a mechanism for an embedder to override a number of these properties, and supporting that even at the C level actually has a measurable performance impact.

[Edit: minor note, when i say "intrepreter" i mean in the general sense -- it could be interpreting an AST, bytecode, or machine code (eg. jit)]

olliej
A: 

Applications that use the Mozilla Spidermonkey implementation of Javascript 1.5 or greater (e.g. Firefox) have access to the __noSuchMethod__ mechanism:

c:\>jsdb
js>x = {};
[object Object]
js>x.__noSuchMethod__ = function(id,args) {writeln('you just called: '+id+'()');}
function (id, args) {
    writeln("you just called: " + id + "()");
}
js>x.foo()
you just called: foo()
js>x.bar()
you just called: bar()
js>
Jason S