Checking existence of properties in JavaScript

前端 未结 3 1341
北荒
北荒 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
    }
    
    0 讨论(0)
  • 2021-01-21 09:48

    Use try catch

    $('#canvas').live('vmousedown', function(e) {
       try {
           console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
       } catch(e) {
           console.error('error ...');
       }
    }
    
    0 讨论(0)
  • 2021-01-21 09:57

    So every time I access a property of an object which is not under my authority, do I have to check existence and type?

    Yes you will have to check the whole path, once at a time, or you can automate it:

    function deepObject(o, s) {
        var ss = s.split(".");
    
        while( o && ss.length ) {
            o = o[ss.shift()];
        }
    
        return o;
    }
    
    var isOk = deepObject(e, "originalEvent.originalEvent.touches.0.webkitForce");
    
    if ( isOk ) {
        // isOk is e.originalEvent.originalEvent.touches.0.webkitForce;
    }
    

    Test case:

    var o = {
      a: {
        b: {
          c: {
            d: {
              e: {
              }
            }
          }
        }
      }
    }
    
    var a = deepObject(o, "a.b.c");
    var b = deepObject(a, "d");
    
    console.log(a); // {"d": {"e": {}}}
    console.log(b); // {"e": {}}
    console.log(deepObject(o, "1.2.3.3")); // undefined
    
    0 讨论(0)
提交回复
热议问题