[英]What does jQuery.fn mean?
这里的fn
是什么意思?
jQuery.fn.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"
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 完成,例如应用不同的类名,但请记住,这只是一个演示概念的演示)
这个答案有一个完整的扩展的好例子。
在 jQuery 源代码中,我们有jQuery.fn = jQuery.prototype = {...}
因为jQuery.prototype
是一个对象,所以jQuery.fn
的值只是对jQuery.prototype
已经引用的同一对象的引用。
要确认这一点,您可以检查jQuery.fn === jQuery.prototype
如果评估为true
(确实如此),则它们引用相同的对象
$.fn是jQuery.prototype的别名,它允许您使用自己的函数扩展 jQuery。
例如:
$.fn.something = function{}
将允许您使用
$("#element").something()
$.fn也是jQuery.fn 的同义词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.