jQuery源代码问题 [英] JQuery source code questions

查看:79
本文介绍了jQuery源代码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于以下代码段,我有两个问题.

I got two questions about following code snippet.

(1). 返回新的jQuery.fn.init(选择器,上下文,rootjQuery);"的目的是什么?为什么它在JQuery函数中返回另一个实例?

(1). What is the purpose of "return new jQuery.fn.init( selector, context, rootjQuery );"? Why does it return another instance inside the JQuery function?

(2).为什么将prototype.constructor重新定义为JQuery?

(2). Why prototype.constructor is re-defined as JQuery?

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    },

... ...

jQuery.fn = jQuery.prototype = {
    constructor: jQuery,
    init: function( selector, context, rootjQuery ) {
        var match, elem, ret, doc;

谢谢!

推荐答案

  1. 当将JQuery用作普通函数时,将创建一个新的(类)JQuery实例,并使用new JQuery.fn.init(...)返回该实例.这样,开发人员不必在$(..)之前添加new关键字.
  2. JQuery.fnJQuery.prototype的快捷方式.编写JQuery.fn.customMethod = function(){...}比编写JQuery.prototype.customMethod = ...更方便.由于通常也可以通过$$j访问JQuery,因此引用JQuery.prototype的捷径是$.fn.
  1. When JQuery is called as an ordinary function, a new (class) instance of JQuery is created and returned using new JQuery.fn.init(...). In this way, developers don't have to add the new keyword before $(..).
  2. JQuery.fn is a shortcut for JQuery.prototype. Writing JQuery.fn.customMethod = function(){...} is more convenient than writing JQuery.prototype.customMethod = .... Because JQuery is often also accessible through $ or $j, The shortesy way to refer to JQuery.prototype is $.fn.

这篇关于jQuery源代码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆