-1

Hi I am very new to JS.

return this.foo("abc",function(){ //do something }); 

Can someone tell me what does the above line do?

2
  • 1
    If you're new, what tutorial or book are you learning from? Commented Jun 4, 2011 at 7:03
  • Which part do you need explained? Commented Oct 9, 2024 at 8:35

5 Answers 5

0
  1. It grabs a reference to this, which might be the DOM Window, a DOM element, or any other JavaScript object depending on how and where the above code is being run.
  2. It (skipping ahead) prepares a new anonymous Function that //does something.
  3. It attempts to invoke a method foo on object this, passing in two parameters "abc" and said anonymous Function.

Very often when you see code that passes along an anonymous function (e.g. function(){ ... }), it is in fact holding on to that function in order to execute it not right away but at some later point in time, such as in response to a click event or a timer.

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

Comments

0

looks like this.foo() is a function that returns something. so the return value is, what this.foo() returns.

Comments

0

calls an instance method that gets as parameters a string and a function.

Comments

0

It will return (yeah, like it is in English) the returned result of a function this.foo(...) (in the most simple form, ithe function this.foo(...) return "something" then the code will return "something"). The function this.foo("abc", function(){...}); is itself a function which receives 2 arguments: A string "abc" and a function(). The function this.foo will do something and return "something" to return by the main function. [x]

Comments

0

It calls the function referenced by this.foo and passes two parameters: The string "abc" and an anonymous function function(){ //do something}. It then returns the result.

It is equivalent to:

var a = "abc"; var b = function(){ //do something }; return this.foo(a, b); 

Functions are first class objects in JS so you can pass them around like any other value.


I recommend to have a look at the MDC JavaScript guide.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.