Checking existence of properties in JavaScript

前端 未结 3 1350
北荒
北荒 2021-01-21 09:17

I\'m new to JavaScript and a little bit confused with the duck typing concept. As far as I can tell, I understood the concept. But that leads to a strange consequence in my thou

3条回答
  •  遥遥无期
    2021-01-21 09:43

    As you are using a specific framework to capture your events, i think that you should assume that the originalEvent is always defined. If it isn't, then it is probably a good thing to throw an error as something clearly went wrong somewhere in the capture of the event.

    However, the event could be a MouseEvent or a TouchEvent, also, the webkitForce property may not be supported. These are the kind of cases that you might want to detect :

    // assume that originalEvent is always be defined by jQuery
    var originalEvent = e.originalEvent.originalEvent;
    if (originalEvent instanceof TouchEvent) {  // if touch events are supported
      // the 'touches' property should always be present in a TouchEvent
      var touch = originalEvent.touches[0];
      if (touch) {
          if (touch.webkitForce) {
            // ...
          } else {
            // webkitForce not supported
          }
      }  // else no finger touching the screen for this event
    } else {
       // probably a MouseEvent
    }
    

提交回复
热议问题