测试任何对象的某个特性是否存在 兼容js

function isHostMethod(object, property) {
    var t = typeof object[property];
    return t=='function' ||(!!(t=='object' && object[property])) ||t=='unknown';
}
var obj = {
    name:"melin",
    get:function(){
        console.log("aaa------");
    }
}

var res1 = isHostMethod(obj,'name');
console.log(res1); //false

var res2 = isHostMethod(obj,'get');
console.log(res2); //true

目前使用 isHostMethod()方法还是比较可靠的,因为它考虑到了浏览器的怪异行为。不过也要注意,宿主对象没有义务保持目前的实现方式不变,也不一定会模仿已有宿主对象的行为。所以,这个函数——以及其他类似函数,都不能百分之百地保证永远可靠。作为开发人员,必须对自己要使用某个功能的风险作出理性的估计。

要想深入了解围绕 JavaScript 中能力检测的一些观点,请参考 Peter Michaux 的文章“ Feature Detection: State of the Art Browser Scripting”, 网址为 http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting。

posted @ 2017-07-05 16:43  MiyaMiya  阅读(159)  评论(0编辑  收藏  举报