解释:获取对对象属性的描述对象。数组
let obj = { foo: 123 };
console.log(Object.getOwnPropertyDescriptor(obj, 'foo'))
显示结果:函数
{ configurable: true enumerable: true value: 123 writable: true __proto__: Object }
this
目前,有四个操做会忽略enumerable为 false 的属性。spa
Object.getOwnPropertyDescriptor(Object.prototype, 'toString').enumerable // false Object.getOwnPropertyDescriptor([], 'length').enumerable // false // toString和length属性的enumerable都是false,所以for...in不会遍历到这两个继承自原型的属性。
const obj = { foo: 123, get bar() { return 'abc' } }; Object.getOwnPropertyDescriptors(obj) // { foo: // { value: 123, // writable: true, // enumerable: true, // configurable: true }, // bar: // { get: [Function: bar], // set: undefined, // enumerable: true, // configurable: true } }
prototype
// 格式 Object.setPrototypeOf(object, prototype) // 用法 const o = Object.setPrototypeOf({}, null); // 该方法等同于下面的函数。 function (obj, proto) { obj.__proto__ = proto; return obj; }
例子:code
let proto = {}; let obj = { x: 10 }; Object.setPrototypeOf(obj, proto); proto.y = 20; proto.z = 40; obj.x // 10 obj.y // 20 obj.z // 40
对象
若是第一个参数不是对象,会自动转为对象。可是因为返回的仍是第一个参数,因此这个操做不会产生任何效果。blog
因为undefined和null没法转为对象,因此若是第一个参数是undefined或null,就会报错。继承
Object.getPrototypeOf(obj);
ip
若是参数是undefined或null,它们没法转为对象,因此会报错。
const proto = { foo: 'hello' }; const obj = { find() { return super.foo; } }; Object.setPrototypeOf(obj, proto); obj.find() // "hello" // 上面代码中,对象obj的find方法之中,经过super.foo引用了原型对象proto的foo属性。
JavaScript 引擎内部,super.foo等同于Object.getPrototypeOf(this).foo(属性)或Object.getPrototypeOf(this).foo.call(this)(方法)。
例题:
const proto = { x: 'hello', foo() { console.log(this.x); }, }; const obj = { x: 'world', foo() { super.foo(); } } Object.setPrototypeOf(obj, proto); obj.foo() // "world" // 上面代码中,super.foo指向原型对象proto的foo方法,可是绑定的this却仍是当前对象obj,所以输出的就是world。
var obj = { foo: 'bar', baz: 42 }; Object.keys(obj) // ["foo", "baz"]
Object.values方法返回一个数组,成员是参数对象自身的(不含继承的)全部可遍历(enumerable)属性的键值。
const obj = { 100: 'a', 2: 'b', 7: 'c' }; Object.values(obj) // ["b", "c", "a"]
上面代码中,属性名为数值的属性,是按照数值大小,从小到大遍历的,所以返回的顺序是b、c、a。
Object.entries方法返回一个数组,成员是参数对象自身的(不含继承的)全部可遍历(enumerable)属性的键值对数组。
const obj = { foo: 'bar', baz: 42 }; Object.entries(obj) // [ ["foo", "bar"], ["baz", 42] ]
除了返回值不同,该方法的行为与Object.values基本一致。