jQuery.fn是什么意思?

这里的fn是什么意思?

jQuery.fn.jquery

#1楼

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来完成,例如应用不同的类名,但是请记住,这只是一个演示概念的演示)

这个答案是完整扩展的一个很好的例子。


#2楼

jQuery.fnjQuery.prototype简写形式。 从源代码

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

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

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

#3楼

在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"

#4楼

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

为了确认这一点,您可以检查jQuery.fn === jQuery.prototype是否评估为true (这样做),然后它们引用同一对象

发布了0 篇原创文章 · 获赞 1 · 访问量 2570

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/103909414