好的!首先,这个问题来自一个在 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 () {}
})
})
当 $
启动时,jQuery.prototype.init
启动并返回一个元素数组。但我不明白它是如何添加像 .css
或 .hide
等 jQuery 方法的。到这个数组。
我得到了静态方法。但是无法使用所有这些方法了解它如何返回和元素数组。
最佳答案
我也不喜欢那个图案。它们有一个 init
函数,它是所有 jQuery 实例的构造函数 - jQuery
函数本身只是用 new
创建的对象的包装器:
function jQuery(…) { return new init(…); }
然后,他们将这些实例的方法添加到 init.prototype
对象中。此对象在 jQuery.fn
中作为接口(interface)公开。此外,他们将 jQuery 函数的 prototype
属性设置为该对象 - 对于那些不使用 fn
属性的人。现在你有
jQuery.prototype = jQuery.fn = […]init.prototype
但他们也做了两件[奇怪的]事情:
- 覆盖原型(prototype)对象的
constructor
属性,将其设置为jQuery
函数 - 在
jQuery.fn
上公开init
函数 - 它自己的原型(prototype)。这可能允许 Extending $.fn.init function , 但非常困惑
我认为他们需要/想要做所有这一切以确保万无一失,但他们的代码一团糟——从对象字面量开始,然后分配初始化原型(prototype)。
关于javascript - 值、原型(prototype)和属性的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12143590/