Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposed question: 5 ways to call a JavaScript function? #12

Open
whawker opened this issue Nov 28, 2012 · 8 comments
Open

Proposed question: 5 ways to call a JavaScript function? #12

whawker opened this issue Nov 28, 2012 · 8 comments

Comments

@whawker
Copy link

whawker commented Nov 28, 2012

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

@dpashkevich
Copy link

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

@davemackintosh
Copy link

I second dpashkevich on this. Good question though!

@nathansmith
Copy link
Owner

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

@dpashkevich
Copy link

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

@nathansmith
Copy link
Owner

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

@dpashkevich
Copy link

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

@mpatel3
Copy link

mpatel3 commented Aug 18, 2016

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants
@nathansmith @dpashkevich @davemackintosh @whawker @mpatel3 and others