4

我对遇到的一行 JavaScript 代码有点困惑,我想了解它的用途:

(function ($, window) {

    var example;

    example = function (a, b, c) {
        return new example.fn.init(a, b, C);
    };

    example.fn = example.prototype = {
        init: function (a, b, c) {
            this.a= a;
            this.b= b;
            this.c= c;
        }    
    };

    example.fn.init.prototype = example.fn; //What does this line accomplish?

    $.example = example;


}(window.jQuery, window));

据我了解,有问题的行是将子对象的原型分配给自身,这实际上是基本示例对象的原型……为什么要这样做?

4

2 回答 2

1

您问题中的代码示例实现了一个多功能函数/对象,其方式与 jQuery 对其jQuery(通常别名为$)对象的方式相同。

使用函数创建的对象example()实际上是由example.fn.init()构造函数实例化的。example将' 原型分配给example.fn.init' 可确保由 公开的成员example也由 由 实例化的对象公开init()

jQuery 源代码的相关部分是:

// Define a local copy of jQuery
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 ) {
        // Actual implementation of the jQuery() function...
    }
    // Other jQuery.fn methods...
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
于 2012-08-21T19:09:06.693 回答
1

看起来整个定义example.fn完全没用。(也许它是为了模仿jQuery fn 对象?)

似乎作者希望以下这些调用会产生相同的结果:

var x = $.example(a, b, c); // Build by function call
var y = new $.example.fn.init(a, b, c); // Build by a constructor call

Asexampleexample.fn.init具有相同的原型,x并且y上面定义的将具有相同的接口。以一种麻烦的方式,IMO。

可以使用更简单的语法(也称为自调用构造函数模式)在函数调用中强制执行“类构造函数”行为:

function example(a, b, c) {
    if (!(this instanceof example)) {
        return new example(a, b, c);
    }

    this.a = a;
    this.b = b;
    this.c = c;
}

var x = example(a, b, c); // Constructor invoked by function call
var y = new example(a, b, c); // Constructor invoked explicitly
于 2012-08-21T19:12:52.943 回答