价值,原型和财产的差异 [英] Difference of the value, prototype and property
问题描述
OK!首先,这个问题来自于一个在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
启动并返回一个元素数组。但我无法理解它是如何添加jQuery方法的,如 .css
或 .hide
等。到这个数组。
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:
- 覆盖原型对象的
构造函数
属性,将其设置为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
我认为他们需要/想要做所有这些都是万无一失的,但他们的代码是一团糟 - 从那个对象文字开始,然后分配init原型的东西。
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屋!