美文网首页
Object.getOwnPropertyNames() 与 O

Object.getOwnPropertyNames() 与 O

作者: 简单tao的简单 | 来源:发表于2024-01-07 18:37 被阅读0次

    相同点

    • 都不包括prototype上的属性
        function Person(name){
            this.name = name;
        }
        Person.prototype = {
            age:18,
            sayName: function () {
                console.log(this.name)
            }
        }
    
        let person1 = new Person('litao');
    
        console.log(Object.getOwnPropertyNames(person1)) //['name']
        console.log(Object.keys(person1)) //['name']
    
    • 都不包括Symbol值作为名称的属性
    const _item = Symbol('item')
    const myobject = {
        name: 'Saku',
        age: '21',
        [_item]: 'mysymbol', 
        say() {
            console.log("Hello,world")
        }
    }
    console.log(Object.getOwnPropertyNames(myobject));// ["name", "age", "say"]
    console.log(Object.keys(myobject)) //['name', 'age', 'say']
    

    不同点

    • 对于数组,Object.getOwnPropertyNames()包含一个名为 length 的属性,Object.keys()没有
    const animals = ['dog', 'cat', 'tiger']
    
    Object.keys(animals) // ['0', '1', '2']
    Object.getOwnPropertyNames(animals) // ['0', '1', '2', 'length']
    
    • Object.getOwnPropertyNames(obj) 返回对象 obj 的所有属性(包括可枚举和不可枚举),而Object.keys(obj) 返回所有可枚举的属性。
    const screen = {
        width: 1200,
        height: 800
    }
    Object.defineProperty(screen, 'resolution',{
        value: '2560 x 1440',
        enumerable: false //不可枚举
    })
    
    console.log(Object.getOwnPropertyNames(screen)) // ['width', 'height', 'resolution']
    console.log(Object.keys(screen)) // ['width', 'height']
    

    相关文章

      网友评论

          本文标题:Object.getOwnPropertyNames() 与 O

          本文链接:https://www.haomeiwen.com/subject/ssogndtx.html