最近在一次工作面试中,我被问到了这个问题,具体是关于Javascript的。我想知道正确的回答。
特性检测
、特性推断
和使用User agent
字符串之间到底有什么区别?
最近在一次工作面试中,我被问到了这个问题,具体是关于Javascript的。我想知道正确的回答。
特性检测
、特性推断
和使用User agent
字符串之间到底有什么区别?
功能检测检查一个功能是否存在,例如:
if (window.XMLHttpRequest) {
new XMLHttpRequest();
}
特性inference检查与特性检测类似,但使用另一个函数,因为它假设该特性也将存在,例如:
if (document.getElementsByTagName) {
element = document.getElementById(id);
}
检查UA字符串是一种过时的做法,不应再使用。您不断更改UA检查,并且从新实施的功能中永远不会受益,例如:
if (navigator.userAgent.indexOf("MSIE 7") > -1){
//do something
}
功能检测:实际上是检查功能是否存在
if('localStorage' in window)
功能推断:如果x存在,则我们可以假设y也存在
if('localStorage' in window){
window.sessionStorage.setItem("this-should-exist-too", 1);
}
if (navigator.geolocation) {
// geolocation possible.. do some stuff
}
navigator.userAgent