你能解释一下这个jQuery方法吗?

mrb*_*lah 3 javascript jquery

试图理解jquery如何在幕后工作,有什么区别:

jQuery.fn和jQuery.prototype

jQuery = window.jQuery = window.$ = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context );
},
Run Code Online (Sandbox Code Playgroud)

然后:

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
Run Code Online (Sandbox Code Playgroud)

sea*_*tar 8

第一个片段保证您使用jQuery将始终在jQuery的原型上调用init函数.

$() == jQuery() == new jQuery() == new jQuery.prototype.init()
Run Code Online (Sandbox Code Playgroud)

第二个片段允许您从中访问jQuery的原型fn.通过为fn属性分配函数,它们也被分配给$ .prototype.这允许在从$返回的对象上调用这些方法:

jQuery.fn.example = function() { alert(this.id); }
$('#some-id').example(); // alerts 'some-id'
Run Code Online (Sandbox Code Playgroud)