2

I am a little bit confused regarding the way in which functions are actually called in javascript. Let's suppose we have the following sample code.

var foo = function() {
    console.log("hello world");
}
foo();

First, we create a function object which is referenced by foo, and then we invoke it. I went through the documentation which says that internally foo() actually invokes call() on the function object. This also makes sense, because, I can replace foo() with foo.call() and nothing changes for the example above.

However, let's suppose I wanted to create a function object in the following way:

class Function1 extends Function {
    call() {
        console.log("hello wold");
    }
}
const foo = new Function1();
foo.call();

When using foo.call(), the correct method is invoked. However, when I try to invoke foo(), I was hoping that the call method from Function1 would be invoked which is not the case. I guess I am thinking in the wrong direction here. I just assumed that foo.call() and foo() would be equivalent when executed on function objects which does not seem to be the case. Could somebody give me a hint on how the call resolution actually works.

1
  • 2
    It looks like you're just shadowing Function.prototype.call? Commented May 23, 2019 at 9:48

1 Answer 1

2

When you call a function, the engine invokes [[Call]] (and not call), which is an internal method, not available in your code. If you want to intercept [[Call]], the only way is to create a Proxy with an apply hook:

function foo() {
    console.log('foo')
}

foo = new Proxy(foo, {
    apply(target) {
        console.log('foo called!')
        target()
    }
});

foo()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.