繁体   English   中英

jQuery.fn 是什么意思?

[英]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.fnjQuery.prototype简写。 源代码

jQuery.fn = jQuery.prototype = {
    // ...
}

这意味着jQuery.fn.jqueryjQuery.prototype.jquery的别名,它返回当前的 jQuery 版本。 再次从源代码

// The current version of jQuery being used
jquery: "@VERSION",

在 jQuery 源代码中,我们有jQuery.fn = jQuery.prototype = {...}因为jQuery.prototype是一个对象,所以jQuery.fn的值只是对jQuery.prototype已经引用的同一对象的引用。

要确认这一点,您可以检查jQuery.fn === jQuery.prototype如果评估为true (确实如此),则它们引用相同的对象

$.fnjQuery.prototype的别名,它允许您使用自己的函数扩展 jQuery。

例如:

 $.fn.something = function{}

将允许您使用

$("#element").something()

$.fn也是jQuery.fn 的同义词

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM