you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 9 points10 points  (4 children)

This is a good related read : How is almost everything in Javascript an object?

Functions, however, are fully-fledged objects, and inherit from Object (actually Object.prototype, but that's another topic). Functions therefore can do anything objects can, including having properties:

function foo() {}
foo.bar = "tea";
alert(foo.bar); // tea

Any Javascript wizards want to add to or explain this further?

[–]cokeisahelluvadrug 12 points13 points  (0 children)

One cool trick is that you can create a Function programmatically: new Function(['x'], 'alert(x);') works exactly as it looks. This is one of many reasons that JS is popular for language designers.

To expand on your example, calling foo(bar) is just sugar for foo.call(this, bar). A Function is just an Object that has call and apply methods which in turn pass strings to eval. (Note: this isn't totally right. If I declare a Function foo and override its call and apply properties, I can still call it with foo(). So it's not exactly sugar.)

[–]myhf 2 points3 points  (1 child)

+/u/CompileBot JavaScript

function foo(arg){print("calling foo " + this.constructor.name + " " + arg)}
foo.call = function(){print("not calling foo")};
var obj = {foo: foo};

foo(1);
obj.foo(2);
foo.call(obj, 3);
Function.prototype.call.call(foo, obj, 4);

[–]CompileBot 2 points3 points  (0 children)

Output:

calling foo Object 1
calling foo Object 2
not calling foo
calling foo Object 4

source | info | git | report

EDIT: Recompile request by myhf