解釋:獲取對對象屬性的描述對象。數組
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基本一致。