What does jQuery.fn mean?
What does jQuery.fn mean?
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"
回答2
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.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-07-06 out
2017-07-06 TortoiseSvn安装的时候,将svn的命令行工具单独隔离出来
2015-07-06 Binary to Text (ASCII) Conversion
2015-07-06 Pizza pieces