值、原型和属性的区别 [英] Difference of the value, prototype and property
问题描述
好的!首先,这个问题来自一个在 jQuery 世界中挖掘得太深(并且可能迷路)的人.
OK! First of all this question comes from a man who digs too deep (and posibly get lost) in the jQuery universe.
在我的研究中,我发现 jquery 的主要模式是这样的(如果需要更正是好的):
In my reserch I discovered the jquery's main pattern is something like this (If needed correction is wellcomed):
(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 方法.到这个数组.
When $
initiates the jQuery.prototype.init
initiates and returns an array of elements. But i could not understand how it adds the jQuery method like .css
or .hide
,etc. to this array.
我得到了静态方法.但是无法获得所有这些方法的返回方式和元素数组.
I get the static methods. But could not get how it returns and array of elements with all those methods.
推荐答案
我也不喜欢那种模式.它们有一个 init
函数,它是所有 jQuery 实例的构造函数——jQuery
函数本身只是一个用 new
创建对象的包装器:
I don't like that pattern either. They have an init
function, which is the constructor of all jQuery instances - the jQuery
function itself is just a wrapper around that object creation with new
:
function jQuery(…) { return new init(…); }
然后,他们将这些实例的方法添加到 init.prototype
对象中.该对象在 jQuery.fn
中作为接口公开.此外,他们将 jQuery 函数的 prototype
属性设置为该对象 - 对于那些不使用 fn
属性的人.现在你有
Then, they add the methods of those instances to the init.prototype
object. This object is exposed as an interface at jQuery.fn
. Also, they set the prototype
property of the jQuery function to that object - for those who don't use the fn
property. Now you have
jQuery.prototype = jQuery.fn = […]init.prototype
但他们也做了两件[奇怪的]事情:
But they also do two [weird] things:
- 覆盖原型对象的
constructor
属性,将其设置为jQuery
函数 - 在
jQuery.fn
上公开init
函数 - 它自己的原型.这可能允许扩展 $.fn.init 函数,但非常混乱
- overwriting the
constructor
property of the prototype object, setting it to thejQuery
function - exposing the
init
function onjQuery.fn
- its own prototype. This might allow Extending $.fn.init function, but is very confusing
我认为他们需要/想要做这一切以防止万无一失,但他们的代码一团糟——从那个对象文字开始,然后分配初始化原型.
I think they need/want to do all this to be fool-proof, but their code is a mess - starting with that object literal and assigning the init prototype things afterwards.
这篇关于值、原型和属性的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!