javascript-quiz icon indicating copy to clipboard operation
javascript-quiz copied to clipboard

Proposed question: 5 ways to call a JavaScript function?

Open whawker opened this issue 13 years ago • 8 comments

This is a question I was once asked in a job interview. Might be appropriate here.

http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx

whawker avatar Nov 28 '12 12:11 whawker

+1, only I would rather call it "5 ways to set function execution context"

dpashkevich avatar Nov 28 '12 12:11 dpashkevich

I second dpashkevich on this. Good question though!

davemackintosh avatar Nov 28 '12 13:11 davemackintosh

Good suggestion, I don't disagree that it's good knowledge to have.

But, I feel like aspects of that blog post are already covered…

  • apply()
  • call()
  • using constructors
  • global scope

nathansmith avatar Nov 28 '12 15:11 nathansmith

Right, but it's a less direct question. You can see how the person understands that all above is connected.

dpashkevich avatar Nov 28 '12 15:11 dpashkevich

I'm up for adding it. Care to write a question, and an example answer?

nathansmith avatar Nov 28 '12 16:11 nathansmith

I kept going back and forth with the question phrasing, here's the best I've come up so far:

Question Can you think of 5 different ways a this can be set when calling a function?

Answer

    1. Global function call
foo();  // this === global inside the function
    1. Method call
obj.foo();  // this === obj inside the function
  • 3,4. Function.call() and Function.apply()
foo.call(obj, param1, param2, param2);  // this === obj
foo.apply(obj, [param1, param2, param2]);  // this === obj
    1. Constructor call
new Foo();  // this === empty object with Foo's prototype

dpashkevich avatar Nov 28 '12 16:11 dpashkevich

+1

mpatel3 avatar Aug 18 '16 08:08 mpatel3