[英]Checking existence of hash key without hasOwnProperty in 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。 如果不是,那么拋出錯誤可能是一件好事,因為事件捕獲中的某些地方顯然出現了問題。
但是,事件可能是MouseEvent或TouchEvent ,也可能不支持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.