hasOwnProperty和in属性操作

2017-02-25  本文已影响0人  码农的世界你不懂

in操作符

用来检查对象中是否存在某个属性(不区分实例属性和原型属性)

<script>

    //01 提供一个构造函数
    function Person(name) {
        this.name = name;
    }

    //02 设置构造函数的原型对象的属性
    Person.prototype.sayHello = function () {
        console.log("hello");
    }

    //03 创建对象
    var p1 = new Person();

    //04 使用in关键字判断对象中是否存在以下属性:name age sayHello
    console.log("age" in p1);       //false
    console.log("name" in p1);      //true
    console.log("sayHello" in p1);  //true

</script>

hasOwnProperty方法

<script>

    //01 提供一个构造函数
    function Person(name) {
        this.name = name;
    }

    //02 设置构造函数的原型对象的属性
    Person.prototype.sayHello = function () {
        console.log("hello");
    }

    Person.prototype.des = "默认的描述信息";

    //03 创建对象
    var p1 = new Person();

    //04 使用hasOwnProperty方法判断该属性是否是对象的实例属性
    console.log(p1.hasOwnProperty("age"));       //false
    console.log(p1.hasOwnProperty("name"));      //true
    console.log(p1.hasOwnProperty("sayHello"));  //false
    console.log(p1.hasOwnProperty("des"));       //false

</script>

某个属性是否存在且只存在于原型属性中

<script>

    //01 提供一个构造函数
    function Person(name) {
        this.name = name;
    }

    //02 设置构造函数的原型对象的属性
    Person.prototype.sayHello = function () {
        console.log("hello");
    };

    Person.prototype.des = "默认的描述信息";

    //03 创建对象
    var p1 = new Person();


    function isProperty(obj, property) {
        return !obj.hasOwnProperty(property) && (property in obj);
    }

    console.log(isProperty(p1, "constructor"));    //true
    console.log(isProperty(p1, "age"));            //false
    console.log(isProperty(p1, "name"));           //false
    console.log(isProperty(p1, "des"));            //true
    console.log(isProperty(p1, "sayHello"));        //true
    console.log(p1);

</script>

上一篇 下一篇

猜你喜欢

热点阅读