javascript-quiz
javascript-quiz copied to clipboard
Proposed question: 5 ways to call a JavaScript function?
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
+1, only I would rather call it "5 ways to set function execution context"
I second dpashkevich on this. Good question though!
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
Right, but it's a less direct question. You can see how the person understands that all above is connected.
I'm up for adding it. Care to write a question, and an example answer?
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
-
- Global function call
foo(); // this === global inside the function
-
- Method call
obj.foo(); // this === obj inside the function
- 3,4.
Function.call()andFunction.apply()
foo.call(obj, param1, param2, param2); // this === obj
foo.apply(obj, [param1, param2, param2]); // this === obj
-
- Constructor call
new Foo(); // this === empty object with Foo's prototype
+1