[英]Can someone explain how one can use preventDefault as an if expression?
在同行审查代码以解决IE中的视差问题的同时,我看到了这段奇怪的代码。
if (window.navigator.userAgent.indexOf("Trident") >= 0) {
$('body').mousewheel(function (event, delta) {
// disable native scroll
if (event.preventDefault) {
event.preventDefault();
} else { // IE fix
event.returnValue = false;
};
$html.stop().animate({
scrollTop: $html.scrollTop() + (-delta * 500)
}, 'slow');
});
}
该代码来自该站点,但是该站点的作者没有提及有人如何将()从函数调用的末尾删除并将其填充到if语句中。 Javascript似乎可以接受,因为它是一种非常宽松的语言,但是我不明白这里正在发生什么的概念?
If this is an IE browser
when some scrolling happens
[*what is this?*]
add jQuery scroll animation to replace it
done
fi
这称为“功能检测” ,是用于确定客户端是否支持某个API的通用模式。 它是您的第一行代码( window.navigator.userAgent.indexOf("Trident") >= 0
)所做的“浏览器检测”的首选。 检查用户代理字符串不仅是始终要移动的全职工作,而且用户代理字符串很容易被欺骗,即使不正确,也不总是很准确。
您的特定用例源于Internet Explorer在IE 9之前不支持preventDefault()
的事实,因此,如果您的代码需要在支持该标准以及IE 8或更低版本的浏览器中工作,则需要停止事件适合适当客户的正确方法。
在JavaScript中,对象属性不过是键而已,从技术上讲,“方法”是不存在的。 函数是一等公民(它们是数据),可以像其他任何数据一样简单地存储在属性中。 您可以像访问任何对象属性一样直接(作为数据)访问该函数:
var myObj = { foo:"something", bar:function(){ console.log("bar says hello"); } }; console.log(myObj.foo); // Just accessing the value of the foo property console.log(myObj.bar); // Just accessing the value of the bar property
但是,可以调用函数,并且在JavaScript中,调用运算符是()
。 因此,如果您查找可以调用的东西并想调用它,只需在其末尾添加()
:
var myObj = { foo:"something", bar:function(){ console.log("bar says hello"); } }; myObj.bar(); // Accessing the value of the bar property and invoking the result
因此,如果对象具有特定的属性(键)并对其进行查询,则将获得其值。 在我们通常称为“方法”的情况下,值将是存储在属性中的函数。 并且,如果属性(键)不存在,您将得到undefined
返回给您。
考虑到所有这些,我们可以继续讨论一个相关主题...
检索值时,可以将其视为“真实的”或“虚假的”,这只是意味着,如果将值转换为布尔值,它将转换为true
还是false
。 false
,empty( ""
), null
, undefined
和0
值是虚假的,其他所有东西都是真实的。
以下尝试获取event
对象的preventDefault
属性值:
// Notice we're not calling the function (no parenthesis)
// We're just retrieving the value of the property
if(event.preventDefault)
在支持preventDefault()
用户代理中,将返回本机函数,由于它处于if
条件,因此它将转换为布尔值。 它将在此处转换为true
,然后输入if
语句的true
分支。 如果该属性不存在,则返回undefined
,它将转换为false
并输入false
分支。
另一种查找属性是否存在的方法是in
运算符:
if(preventDefault in event)
这将检查对象的继承属性以及“自己的”属性。
这是另一个例子。 您会注意到,以下代码中的实际位置都不会实际调用foo
(在控制台中不会看到“ foo被调用!”)。 我们只查找foo
属性的值:
var myObj = { foo : function(){ console.log("foo was invoked!"); } }; // Notice were not calling foo (no parenthesis). We're just looking up its value: console.log(myObj.foo); // What about a property that doesn't exist? console.log(myObj.foo2); // undefined // And we can convert that value to a Boolean console.log(Boolean(myObj.foo)); // true console.log(Boolean(myObj.foo2)); // false if(myObj.foo){ console.log("foo exists"); } else { console.log("foo doesn't exist"); }
这是一个警卫声明。 JavaScript中的function
仅仅是对象,因此此代码preventDefault
存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.