阅读有关事件对象及其构造函数的 jQuery 文档 $.Event()
我明白了:
The
new
operator is optional [when calling the constructor].
太酷了! jQuery 的人是怎么玩出这样的把戏的?
最佳答案
John Resig 很好地解释了这一点:http://ejohn.org/apps/learn/#36和 http://ejohn.org/apps/learn/#38
基本上,Event
是一个函数和一个对象(函数就是对象)。 Event 的第一行检查它是作为函数还是作为 Event 对象的实例调用(使用 new 运算符)。
如果您正在寻找 jQuery 的具体操作方式,请查看 jQuery source 的第 3134-3138 行。 :
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src, props );
}
对此的解释位于 the jQuery forms .
基本上,在第 3178-3194 行,preventDefault 事件被添加到事件原型(prototype)中。如果事件是用new
实例化的,它将被赋予这个preventDefault方法。否则,它不会被定义。
关于jquery - 可选 `new` 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7303614/