【发布时间】:2011-05-04 06:11:38
【问题描述】:
这里的fn是什么意思?
jQuery.fn.jquery
【问题讨论】:
标签: javascript jquery
这里的fn是什么意思?
jQuery.fn.jquery
【问题讨论】:
标签: javascript jquery
在 jQuery 中,fn 属性只是prototype 属性的别名。
jQuery 标识符(或$)只是一个构造函数,用它创建的所有实例都继承自构造函数的原型。
一个简单的构造函数:
function Test() {
this.a = 'a';
}
Test.prototype.b = 'b';
var test = new Test();
test.a; // "a", own property
test.b; // "b", inherited property
一个类似于 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"
【讨论】:
return this 允许chaining,所以你可以这样做foo("bar").myPlugin().otherPlugin()
function func1 (a) { ... },属性将是此处的“a”变量var foo = {}; foo.a = 'a'。
fn 字面意思是 jquery prototype。
这行代码在源码中:
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
但fn 背后的真正工具是它可以将您自己的功能挂接到 jQuery 中。请记住,jquery 将是您的函数的父作用域,因此 this 将引用 jquery 对象。
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
所以这是一个简单的例子。假设我想做两个扩展,一个放置蓝色边框,将文本着色为蓝色,我希望它们链接起来。
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;
};
现在您可以将它们用于这样的类:
$('.blue').blueBorder().blueText();
(我知道这最好用 css 完成,例如应用不同的类名,但请记住,这只是一个演示概念)
This answer 有一个很好的完整扩展示例。
【讨论】:
each 吗? $.fn.blueBorder = function(){ this.css("border","solid blue 2px"); return this; }; 可以正常工作,因为 .css() alerady 会遍历元素。
css 函数将自动在每个内部迭代它们。这只是显示this 中差异的一个示例,其中外部对象是 jquery 对象,内部对象引用元素本身。
jQuery.fn 定义为jQuery.prototype 的简写。来自source code:
jQuery.fn = jQuery.prototype = {
// ...
}
这意味着jQuery.fn.jquery 是jQuery.prototype.jquery 的别名,它返回当前的jQuery 版本。再次来自source code:
// The current version of jQuery being used
jquery: "@VERSION",
【讨论】:
$.fn 是 jQuery.prototype 的别名,它允许您使用自己的函数扩展 jQuery。
例如:
$.fn.something = function{}
将允许您使用
$("#element").something()
$.fn 也是 jQuery.fn 的同义词。
【讨论】:
在 jQuery 源代码中,我们有 jQuery.fn = jQuery.prototype = {...},因为 jQuery.prototype 是一个对象,jQuery.fn 的值将只是对 jQuery.prototype 已经引用的同一对象的引用。
要确认这一点,您可以检查jQuery.fn === jQuery.prototype,如果它评估true(确实如此),那么它们引用相同的对象
【讨论】: