需要帮助解密JQuery示例

cho*_*obo 2 jquery

我刚刚开始学习jQuery和OO Javascript,所以我想弄清楚哪个属于哪个以及它们做了​​什么.我在JQuery文档中遇到了这段代码

(function($sub) {

  $sub // a subclass of jQuery
  $sub === jQuery; //= false

  $sub.fn.myCustomMethod = function(){
    return 'just for me';
  }

  $sub(document).ready(function() {
    $sub('body').myCustomMethod(); //= 'just for me'
  });

})(jQuery.subclass());
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 为什么(函数被()包围?
  2. 这是什么意思(jQuery.subclass()); ?这是一个JQuery的东西或常规JavaScript的一部分?

谢谢

Ray*_*nos 5

(1)自我调用功能

function() {

}();
Run Code Online (Sandbox Code Playgroud)

它们都是无效的,因为它们会导致语法错误,并且在底部调用它会让人感到困惑.

这就是JavaScript社区(在自调用函数开始时使用的原因,让代码的其他读者知道它不是正常的函数.

var o = (function() {

})();
Run Code Online (Sandbox Code Playgroud)

每当我看到一个以(我开始的函数时,我知道它是自我调用的.这意味着它立即执行并o包含函数的返回值而不是函数.

(2)jQuery子类

要小心使用子类依赖于jQuery 1.5.我建议你等待官方发布,而不是使用1.5 RC1,因为有一些错误需要解决.

jQuery.subclass是jQuery 1.5 beta的一部分.这是jQuery的一个新特性,它本质上是jQuery的子类.

这意味着您添加到jQuery.subclass的任何内容都不会添加到jQuery中.jQuery子类具有jQuery的所有功能,但是您添加或更改的任何内容都不会影响"global jquery"

带注释的样本源

// self invoking function. This creates a closure so that anything declared in 
// this function is local and doesn't effect global state
(function($sub) {

  $sub // a subclass of jQuery
  $sub === jQuery; //= false

  // here we extend $.fn with a new method. This actually extends the prototype of $sub
  // $sub.fn === $sub.prototype === $()
  // $sub.fn is actually a new jQuery object. This means that when using $sub we first look
  // for method defined on $sub.fn, and if there aren't any we look on methods defined 
  // on $.fn. A useful feature of this is that you can overwrite methods
  $sub.fn.myCustomMethod = function(){
    return 'just for me';
  }

  // We can "overwrite" methods of jQuery by hiding the original methods.
  $sub.fn.attr = function() {
    alert("new attr!");
    // you can go into $sub.superclass to get the original $ object and call methods there
    $sub.superclass.attr.apply(this, arguments);

  }

  // This calls .ready from the original jQuery
  $sub(document).ready(function() {
    $sub('body').myCustomMethod(); //= 'just for me'
  });

// we pass in a subclass of jquery at the bottom. This means that $sub has all the
// functionality of $ but doesn't change $ itself. 
})(jQuery.subclass());
Run Code Online (Sandbox Code Playgroud)

免责声明 .__proto__已被弃用不好.它仅用于说明jQuery.subclass的原型链是什么样的.

对于那些理解.__proto__(这得到对象的构造函数的原型)

var $sub = jQuery.subclass();
$sub.__proto__ === $sub.fn; // true
$sub.__proto__.__proto__ === $.fn; // true

// example of .__proto__
function constructor() { }
var o = new constructor;
o.__proto__ === constructor.prototype; // true
Run Code Online (Sandbox Code Playgroud)

如果需要进一步解释或者您对其他任何事情感到好奇,请提及它.我可能已经掩饰了一些我认为很明显的东西.