JS判断某一个对象是否拥有某一个属性

333 阅读1分钟

方法一:使用 in

in 的特点: 只要类中或者原型对象中有, 就会返回true

        class Person{
            name = null;
            age = 0;
        }
        Person.prototype.height = 0;
        let p = new Person();
        // in的特点: 只要类中或者原型对象中有, 就会返回true
        console.log("name" in p); // true
        console.log("width" in p); // false
        console.log("height" in p); // true

方法二:hasOwnProperty

判断某一个对象自身是否拥有某一个属性

特点: 只会去类中查找有没有, 不会 去原型对象中查找

        class Person{
            name = null;
            age = 0;
        }
        Person.prototype.height = 0;
        // 需求: 判断某一个对象自身是否拥有某一个属性
        let p = new Person();
        // 特点: 只会去类中查找有没有, 不会去原型对象中查找
        console.log(p.hasOwnProperty("name")); // true
        console.log(p.hasOwnProperty("height")); // false

学习笔记❥(^_-)