为什么jQuery这样做:jQuery.fn.init.prototype = jQuery.fn? [英] Why jQuery do this: jQuery.fn.init.prototype = jQuery.fn?
问题描述
小问题是为什么jQuery要做什么
Little extended question is why jQuery do
jQuery.fn = jQuery.prototype = {
init: function() {...},
f1: function() {...},
...
};
jQuery.fn.init.prototype = jQuery.fn;
为什么不简单地添加 f1()
等进入 init.prototype
?它只是审美还是有一些深刻的想法?
Why not simply add f1()
etc into init.prototype
? Is it only aesthetic or there are some deep ideas?
推荐答案
jQuery.fn只是jQuery.prototype的别名。我认为它的定义是出于审美和打字的原因。
The jQuery.fn is just an alias for jQuery.prototype. I suppose it is defined for aesthetic and less typing reasons.
所以
jQuery.fn.init.prototype = jQuery.fn;
实际上是
jQuery.prototype.init.prototype = jQuery.prototype;
为什么需要这样做,这论坛帖子很有帮助:
As why this needs to be done, this forum post is helpful:
它为init()函数提供了与jQuery对象相同的
原型。所以当你在return new jQuery.fn.init(
selector,context);中调用init()作为构造函数
时,
;声明,
使用该原型作为
构造的对象。这让init()
替代jQuery构造函数
本身。
It gives the init() function the same prototype as the jQuery object. So when you call init() as a constructor in the "return new jQuery.fn.init( selector, context );" statement, it uses that prototype for the object it constructs. This lets init() substitute for the jQuery constructor itself.
你实现的是对象从jQuery.fn.init构造函数返回,可以访问jQuery方法。
What you achieve is that the object returned from a jQuery.fn.init constructor has access to jQuery methods.
这篇关于为什么jQuery这样做:jQuery.fn.init.prototype = jQuery.fn?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!