这里的fn是什么意思?
jQuery.fn.jquery
这里的fn是什么意思?
jQuery.fn.jquery
当前回答
美元的。fn是jQuery的别名。它允许你用自己的函数来扩展jQuery。
例如:
$.fn.something = function{}
会允许你使用吗
$("#element").something()
美元的。fn也是jQuery.fn的同义词。
其他回答
在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"
jQuery。fn是jQuery.prototype的简写。从源代码:
jQuery.fn = jQuery.prototype = {
// ...
}
这意味着jQuery.fn.jquery是jQuery.prototype的别名。返回当前jquery版本。同样来自源代码:
// The current version of jQuery being used
jquery: "@VERSION",
Fn字面上指的是jquery原型。
这行代码在源代码中:
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演示
$.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,如应用不同的类名,但请记住,这只是一个演示的概念)
这个答案有一个完整的扩展的好例子。
美元的。fn是jQuery的别名。它允许你用自己的函数来扩展jQuery。
例如:
$.fn.something = function{}
会允许你使用吗
$("#element").something()
美元的。fn也是jQuery.fn的同义词。
在jQuery源代码中我们有jQuery。fn = jQuery。原型={…} jQuery。prototype是jQuery的值对象。fn将只是对jQuery相同对象的引用。原型已经引用。
要确认这一点,可以检查jQuery。fn === jQuery。原型如果它的值为真(它确实),那么它们引用相同的对象