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();
调用。