价值、原型和属性的差异
Difference of the value, prototype and property
OK!首先,这个问题来自一个在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
启动并返回一个元素数组。但是我不明白它如何将 jQuery 方法(如 .css
或 .hide
等(添加到这个数组中。
我得到静态方法。但是无法使用所有这些方法获取它如何返回和元素数组。
我也不喜欢这种模式。它们有一个init
函数,它是所有 jQuery 实例的构造函数 - jQuery
函数本身只是使用该对象创建的包装器new
:
function jQuery(…) { return new init(…); }
然后,他们将这些实例的方法添加到init.prototype
对象。此对象在 jQuery.fn
处作为接口公开。此外,他们将 jQuery 函数的 prototype
属性设置为该对象 - 适用于不使用 fn
属性的用户。现在你有
jQuery.prototype = jQuery.fn = […]init.prototype
但他们也做了两件[奇怪的]事情:
- 覆盖原型对象的
constructor
属性,将其设置为jQuery
函数 - 在
jQuery.fn
上公开init
函数 - 它自己的原型。这可能允许扩展 $.fn.init 功能,但非常令人困惑
我认为他们需要/想要做所有这些事情才能做到万无一失,但他们的代码是一团糟 - 从该对象文字开始,然后分配 init 原型的东西。
如果您将 API 视为方法的外部集合,并将 jQuery 函数视为包装器,则更容易理解。
它基本上是这样构造的:
function a() { return new b();}
a.prototype.method = function() { return this; }
function b() {}
b.prototype = a.prototype;
除了a
是jQuery
,b
是jQuery.prototype.init
.
我确信 Resig 将 api 构造函数放在 init 原型中有他的理由,但我看不到它们。除了Bergi提到的那些之外,还有一些奇怪的事情:
1(模式需要从jQuery.fn.init.prototype
到jQuery.prototype
的参考副本,这允许一个奇怪的无限循环:
var $body = new $.fn.init.prototype.init.prototype.init.prototype.init('body');
2(每个jQuery集合实际上是jQuery.fn.init
的一个实例,但由于它们引用了相同的原型对象,它欺骗我们"认为"该集合是jQuery
的实例。你可以像这样做同样的巫术:
function a(){}
function b(){}
a.prototype = b.prototype;
console.log( new b instanceof a); // true
console.log( new a instanceof b); // true
旁注:我个人使用以下构造函数模式,结果相似,没有怪异之处:
var a = function(arg) {
if (!(this instanceof a)) {
return new a(arg);
}
};
a.prototype.method = function(){ return this; };
- 如何从对象的原型方法访问JavaScript对象属性
- 附加到原型属性的Do函数没有闭包
- 日期原型属性
- 价值、原型和属性的差异
- 使用闭包创建原型中引用的私有属性
- 为什么属性存在于对象实例上,即使其原型发生了更改
- 为什么在原型中定义属性被视为反模式
- JS构造函数的原型属性与其原型之间的区别
- 为什么函数对象的实例没有继承函数原型属性
- 组件是HTML5的属性还是原型.js的东西
- 为什么浏览器显示原型属性不同
- 使用原型对象向javascript对象添加自定义属性和方法的建议
- Javascript设置&阴影属性(原型链)
- 高图表热图 未捕获类型错误:无法读取未定义的属性“原型”
- 无法使用服务AngularJS - “无法读取未定义的属性'原型'”
- 未捕获的类型错误:无法读取未定义的属性“原型”
- 如何在DOM object的构造函数中添加属性.原型在Internet Explorer<=IE8
- 扩展类不能读取未定义的属性原型
- 未捕获的类型错误:无法读取未定义的 sails.io.js 的属性“原型”
- 升级到量角器4后无法读取未定义的属性“原型”