Lup*_*pus 5 javascript oop jquery reverse-engineering
好!首先,这个问题来自于一个在jQuery世界中挖掘太深(并且可能会迷路)的人.
在我的研究中,我发现jquery的主要模式是这样的(如果需要更正是很好的):
(function (window, undefined) {
jQuery = function (arg) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(arg);
},
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function (selector, context, rootjQuery) {
// get the selected DOM el.
// and returns an array
},
method: function () {
doSomeThing();
return this;
},
method2: function () {
doSomeThing();
return this;,
method3: function () {
doSomeThing();
return this;
};
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function () {
//defines the extend method
};
// extends the jQuery function and adds some static methods
jQuery.extend({
method: function () {}
})
})
Run Code Online (Sandbox Code Playgroud)
当$发起jQuery.prototype.init启动并返回元件的阵列.但我无法理解它是如何添加像.css或.hide等的jQuery方法.到这个数组.
我得到了静态方法.但无法获得它返回的方式以及所有这些方法的元素数组.
我也不喜欢那种模式.它们有一个init函数,它是所有jQuery实例的构造jQuery函数- 函数本身只是创建对象的包装器new:
function jQuery(…) { return new init(…); }
Run Code Online (Sandbox Code Playgroud)
然后,他们将这些实例的方法添加到init.prototype对象中.此对象作为接口公开jQuery.fn.此外,他们将prototypejQuery函数的属性设置为该对象 - 对于那些不使用该fn属性的人.现在你有了
jQuery.prototype = jQuery.fn = […]init.prototype
Run Code Online (Sandbox Code Playgroud)
但他们也做了两件事[奇怪]:
constructor原型对象的属性,将其设置为jQuery函数init函数jQuery.fn- 它自己的原型.这可能允许扩展$ .fn.init函数,但是非常令人困惑我认为他们需要/想要做所有这些都是万无一失的,但他们的代码是一团糟 - 从该对象文字开始,然后分配init原型的东西.