判断属性存在于对象中还是原型中

同时使用in操作符和hasOwnProrotype()就可以确定判断属性是存在原型中还是实例中,使用hasOwnPrototype()时,
只有存在实例中的时候返回true,否则返回false。使用in操作符的时候,只要属性存在,不管在原型中还是实例中,都返回true.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
</body>
<script type="text/javascript">
    function hasPropertyProperty(object,name){
        return !object.hasOwnProperty(name)&&(name in object);
    };
    function Person(){}
    Person.prototype.name="xiaofei";
    Person.prototype.age=22;
    Person.prototype.job="Software Engineer";
    Person.prototype.sayName=function(){
        alert(this.name);
    };
    var person=new Person();
    alert(hasPropertyProperty(person,"name"));
    person.name="xiaoming";
    alert(hasPropertyProperty(person,"name"));

</script>
</html>

posted @ 2016-11-06 21:09  逗比煎饼侠  阅读(171)  评论(0编辑  收藏  举报