Reputation: 316
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;
Upvotes: 1
Views: 68
Reputation: 15404
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.
Upvotes: 1
Reputation: 10492
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
Upvotes: 1
Reputation: 3537
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.
Upvotes: 1