繁体   English   中英

检查JavaScript中是否存在属性

[英]Checking existence of properties in JavaScript

我是JavaScript新手,对鸭子打字概念有点困惑。 据我所知,我理解这个概念。 但这导致了我思想中的奇怪后果。 我将用以下示例解释:

我目前正在使用jQuery Mobile开发移动网络应用程序。 有一次我捕获了画布的vmousedown事件。 我对触摸的压力很感兴趣。 我找到了Touch.webkitForce属性。

$('#canvas').live('vmousedown', function(e){
    console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
}

使用远程调试 Chrome时,此工作正常。 但是在Opera Firefly中测试时抛出异常,因为originalEvent属性不是触摸事件,而是click事件。

所以每当我访问不属于我权限的对象的属性时,我是否必须检查存在并键入?

if( e.originalEvent &&
    e.originalEvent.originalEvent &&
    e.originalEvent.originalEvent.touches && 
    e.originalEvent.originalEvent.touches[0] && 
    e.originalEvent.originalEvent.touches[0].webkitForce) {

    console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
}

可以请有人为我澄清一下吗?

所以每当我访问不属于我权限的对象的属性时,我是否必须检查存在并键入?

是的,你必须一次检查整个路径,或者你可以自动化它:

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;
}

测试用例:

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

使用try catch

$('#canvas').live('vmousedown', function(e) {
   try {
       console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
   } catch(e) {
       console.error('error ...');
   }
}

当您使用特定框架捕获事件时,我认为您应该假设始终定义originalEvent。 如果不是,那么抛出错误可能是一件好事,因为事件捕获中的某些地方显然出现了问题。

但是,事件可能是MouseEventTouchEvent ,也可能不支持webkitForce属性。 这些是您可能想要检测的案例:

// 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
}

暂无
暂无

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

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