I am trying to learn jquery/javascript by looking at the source code of some websites. I am a bit unsure about the syntax used there:
!function(t) {
"use strict";
function e() {
var e = parseInt(t(window).scrollTop()),
n = 10;
e > n ? a.addClass("new-class") : (a.removeClass("new-class"), t(".sclass").removeClass("fclass"))
}
//...more codes...
}(jQuery),
I just don't really get what exactly is the meaning of that t there. Is it "this" or just any event object? and what does t(window) means? I thought it should be something like t.window? Since t is not a function.
Thanks! Saldtch
t
is a reference to the jQuery
object within the scope of that function. Notice how the function is called:
!function (t) {
// "t" is the jQuery object
}(jQuery);
The function is defined and then immediately invoked with the parameter jQuery
. So when the function is invoked, that parameter being passed is stored in the variable t
. You could name it anything, really:
!function (foo) {
// "foo" is the jQuery object
}(jQuery);
The function is defined inline, so it doesn't have a name, and immediatley gets called with param jQuery. "t" is the formal parameter of the inline function, which gets resolved with the concrete parameter "jQuery".
Shortly, variable t
refers to the jQuery
object (or whatever jQuery variable holds).
That's equivalent to:
function x(t) {
//code in here
}
x(jQuery);
Therefore t
is a local reference in the function to jQuery
.
And, t(window)
is equivalent to jQuery(window)
... and by extension $(window)
.
Insert this code in the function e()
:
console.log(t === jQuery);
You will assert that t
is jQuery
alias indeed in that function.
As already mentioned above, t equals to the jquery object in this case. t(window) means, wrap the window object with the jquery object, so after wrapping it, i can call jquery methods on it. I'm sure you are already familiar with jquery's $(selector) method, which does the same (fair enough).
So, $('#product')
should get the DOM element with id "product" and wrap it inside a jquery object.
Example :
var myProduct = document.querySelector('#product');
myProduct.attr('id'); // error, myProduct doesn't have method attr() because it is not a jquery "instance"
$(myProduct).attr(id); // product, we wrapped the item in a jquery object
Since jquery is named as t in your example, t(window)
is wrapping the window object in jquery. The window object normally doesn't have a scrollTop()
method defined on it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.