What does jQuery.fn mean?
这里的'fn'是什么意思?
window.jQuery.fn.jquery
In jQuery, the fn
property is just an alias to the prototype
property.
The jQuery
identifier (or $
) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.
A simple constructor function:
function Test() {
this.a = 'a';
}
Test.prototype.b = 'b';
var test = new Test();
test.a; // "a", own property
test.b; // "b", inherited property
A simple structure that resembles the architecture of jQuery:
(function() {
var foo = function(arg) { // core constructor
// ensure to use the `new` operator
if (!(this instanceof foo))
return new foo(arg);
// store an argument for this example
this.myArg = arg;
//..
};
// create `fn` alias to `prototype` property
foo.fn = foo.prototype = {
init: function () {/*...*/}
//...
};
// expose the library
window.foo = foo;
})();
// Extension:
foo.fn.myPlugin = function () {
alert(this.myArg);
return this; // return `this` for chainability
};
foo("bar").myPlugin(); // alerts "bar"
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
fn
literally refers to the jquery prototype
.
This line of code is in the source code:
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
But the real tool behind fn
is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this
will refer to the jquery object.
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.
jsFiddle Demo
$.fn.blueBorder = function(){
this.each(function(){
$(this).css("border","solid blue 2px");
});
return this;
};
$.fn.blueText = function(){
this.each(function(){
$(this).css("color","blue");
});
return this;
};
Now you can use those against a class like this:
$('.blue').blueBorder().blueText();
(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)
This answer has a good example of a full fledged extension.
链接地址: http://www.djcxy.com/p/17054.html上一篇: 'var that = this'是什么意思 在JavaScript中的意思是?
下一篇: jQuery.fn是什么意思?