返回博主主页

Object.keys(xxx)与Object.getOwnPropertyNames(xxx)

Object.keys(xxx)与Object.getOwnPropertyNames(xxx)

Object.keys(xxx)只返回xxx可枚举的值

Object.getOwnPropertyNames()方法返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性但不包括Symbol值作为名称的属性)组成的数组。

 

 

 

注意参数为p和Point.prototype的区别:

1.Object.keys(p)、Object.getOwnPropertyNames(p)

console.log(Object.keys(p))
//['x', 'y']
console.log(Object.getOwnPropertyNames(p))
//['x', 'y']

2.Object.keys(Point.prototype)、Object.getOwnPropertyNames(Point.prototype)

console.log(Object.keys(Point.prototype))
//['fun1', 'z', fun2']  只有定义在原型prototype上的结果
console.log(Object.getOwnPropertyNames(Point.prototype))
//['constructor', 'add', 'age', 'fun1', 'z', fun2'],包含所有的结果,无论是否顶底在原型prototype上

 

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    add(a, b) {
        return a + b
    }
    get age() {
        return this._age;
    }
    set age(x) {
        this._age = x;
    }

}
var z = 4;
Object.assign(Point.prototype, {
    fun1() {},
    z
});
Point.prototype.fun2 = function() {}

var p = new Point(1,2);
console.dir({})
console.dir(p)
//console.log(Object.getOwnPropertyNames()) //必须传参数
// console.log(Object.keys(p.prototype)) // 报错
console.log(Object.keys(p))
//['x', 'y']
console.log(Object.keys(Point.prototype))
//['fun1', 'z', fun2']
console.log(Object.getOwnPropertyNames(Point.prototype))
//['constructor', 'add', 'age', 'fun1', 'z', fun2']
console.log(Object.getOwnPropertyNames(p))
//['x', 'y']
console.log(Object.getOwnPropertyNames(new Point(3,4)))
//['x', 'y']
console.log(p.hasOwnProperty("x"))
//true
console.log(p.hasOwnProperty("y"))
//true
console.log(p.hasOwnProperty("z"))
//false
console.log(Point.prototype.hasOwnProperty("z"))
// true

p.age = 100

console.log(p.age)
//使用set age(x){}才能取到值
console.log(p.z)
//4

 

posted @ 2022-02-09 14:29  懒惰的星期六  阅读(93)  评论(0编辑  收藏  举报

Welcome to here

主页