简体   繁体   English

无法触发自制的Event.prototype

[英]Can't trigger self-made Event.prototype

I have this prototype function -> 我有这个原型功能 - >

Event.prototype.eventPreventDefault = function () {
    this.preventDefault ? this.preventDefault() : this.returnValue = false;
}

I call from code by doing this -> 我通过这样做来调用代码 - >

$element.click(function (evt) {
        evt.eventPreventDefault();
}

but I get 但我明白了

Uncaught TypeError: undefined is not a function 未捕获的TypeError:undefined不是函数

What do I do wrong? 我做错了什么? Thanks! 谢谢!

Event objects created by jQuery (and passed into event handlers) are not children of native Events ( 'prefer composition over inheritance' principle ). 由jQuery创建的事件对象(并传递给事件处理程序)不是本机事件的子项( “首选组合而不是继承”原则 )。 They have their own set of methods (set on jQuery.Event.prototype ): 他们有自己的一组方法 (在jQuery.Event.prototypejQuery.Event.prototype ):

jQuery.Event.prototype = {
    constructor: jQuery.Event,
    isDefaultPrevented: returnFalse,
    isPropagationStopped: returnFalse,
    isImmediatePropagationStopped: returnFalse,

    preventDefault: function() {
        var e = this.originalEvent;

        this.isDefaultPrevented = returnTrue;

        if ( e && e.preventDefault ) {
            e.preventDefault();
        }
    },
    stopPropagation: function() {
        var e = this.originalEvent;

        this.isPropagationStopped = returnTrue;

        if ( e && e.stopPropagation ) {
            e.stopPropagation();
        }
    },
    // ... and so on.
};

As you see, these methods usually call the same-named methods of the original Event (stored in jQuery.Event instance's originalEvent property). 如您所见,这些方法通常调用原始Event的同名方法(存储在jQuery.Event实例的originalEvent属性中)。 The point is, jQuery.Event doesn't have Event.prototype in its inheritance chain, hence any modification of the latter is destined to have no effect on the former. 关键是, jQuery.Event在其继承链中没有Event.prototype ,因此对后者的任何修改都注定对前者没有影响。

The bottom line: to extend Events passed into jQuery event handlers, extend jQuery.Event.prototype instead of Event.prototype . 底线:扩展传递给jQuery事件处理程序的事件,扩展jQuery.Event.prototype而不是Event.prototype

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM