JavaScript:将子对象的原型分配给自身?
我对我遇到的一行JavaScript代码有点困惑,我想了解它的用途:JavaScript:将子对象的原型分配给自身?,javascript,jquery,prototype,Javascript,Jquery,Prototype,我对我遇到的一行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) {
(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));
据我所知,所讨论的行是将子对象的原型分配给它自己,它实际上是基本示例对象的原型。。。为什么会有人想这样做 问题中的代码示例实现了一个多用途函数/对象,与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;
看来example.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
由于example
和example.fn.init
具有相同的原型,上述定义的x
和y
将具有相同的接口。以一种笨拙的方式,IMO
可以使用更简单的语法(也称为自调用构造函数模式)在函数调用中强制执行“类似构造函数”的行为:
可能的重复我今天早上只是从“如何确保总是使用new
调用此函数”的角度考虑这个问题(学术上)。。。好办法
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