1

Below is a code used in many userscripts:

function with_jquery(f) {
var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + f.toString() + ")(jQuery)";
document.body.appendChild(script);
};

I understood everything in it except this line:

  script.textContent = "(" + f.toString() + ")(jQuery)";

I knew that text content sets the text content of the script( of course), but I just can't understand everything after the =. shouldn't this be:

   script.textContent = string; 
Mark
  • 316
  • 2
  • 10

3 Answers3

1

By wrapping the string with ( f.toString() )(jQuery) the user is setting up the string to be executed as an immediately invoked function expression, with the jQuery object passed into that function.

We would expect, then, that f.toString() would look something like

function($){ [doing something...] }

So that the jQuery object will stand in for $

The new string will still have to be evaluated, of course.

Faust
  • 15,130
  • 9
  • 54
  • 111
1

The function creates a script element with this code:

(content-of-f)(jQuery)

So if you pass a string containing a function (eg function($) { do something }) and the function gets executed while jQuery is passed for the $-parameter.

Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
1

anonymous function:

(function(){
  //Normal code goes here
})

The really interesting part is what happens when we add this right at the end:

();

Those two little brackets cause everything contained in the preceding parentheses to be executed immediately.

When you write (jquery)() as below:

(function(a){
  console.log(a === jquery); //Returns 'true'
})(jquery);

All references to ‘jquery’ in your code can be renamed to ‘a’. check this CHEK THIS

Manish Kumar
  • 10,214
  • 25
  • 77
  • 147