javascript - 一个关于jquery源码的问题: jQuery.fn.init.prototype = jQuery.fn

查看:93
本文介绍了javascript - 一个关于jquery源码的问题: jQuery.fn.init.prototype = jQuery.fn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

 var jQuery = (function() {
       var jQuery = function( selector, context ) {
           return new jQuery.fn.init( selector, context, rootjQuery );
       }

       // jQuery对象原型
       jQuery.fn = jQuery.prototype = {
           constructor: jQuery,
           init: function( selector, context, rootjQuery ) {
              //do something

           }

       };
       jQuery.fn.init.prototype = jQuery.fn;

jquery源码中,通过jQuery.fn.init.prototype = jQuery.fn;这一句将jQuery.prototype的方法挂载到new出来的新的jquery对象上,但是当我使用

jQuery.extend({
  sayhello:function(){
      console.log("Hello,This is jQuery Library");
    }
})

extend来定义一个新方法时,这个方法按理来说应该是
1.既绑定到了jQuery.prototype上 原因:jQuery.extend = jQuery.fn.extend=function(){}
2.也绑定到了new出来的新jquery对象上,原因:jQuery.fn.init.prototype = jQuery.fn

但是!这种情况下我$("div").sayhello()却报错Uncaught TypeError: $(...).sayhello is not a function(…)
$.sayhello();却可以成功Hello,This is jQuery Library
很显然这个sayhello成为了jquery原型的方法,但是并没有挂载到new出来的新的jquery对象上
请问这种情况应该怎么理解呢?

解决方案

jQuery.extend = jQuery.fn.extend=function(){}这一句只是表明 jQuery 和 jQuery的原型都指定了同一个继承方法,并不代表你调用了jQuery.extend同时调用了jQuery.fn.extend

你用的jQuery.extend只是继承到了jQuery这个全局函数上,只能$.sayhello();调用。

这篇关于javascript - 一个关于jquery源码的问题: jQuery.fn.init.prototype = jQuery.fn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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