昨天在思考一个问题,jQuery为什么使用init()来创建对象,不用new,现在把我思考结果分享下:
首先看下创建jQuery对象的过程:
function jQuery(){
return new jQuery.prototpye.init();
}
jQuery.prototype.init=function(){};
jQuery.prototype.css=function(){};
jQuery.fn.init.prototype=jQuery.fn;
//调用方法
jQuery().css();
首先,通过return调用init()函数,这样在调用时,直接使用jQuery(),就可以创建jQuery对象了,无需使用new操作符,简化了操作。然后,把jQuery.fn即jQuery.prototype赋给init.prototype,这样,通过init()创建的对象就可以访问jQuery原型中的方法了。