Object.getOwnPropertyDescriptor()
Object.getOwnPropertyDescriptor(obj, prop) 静态方法返回自身属性描述符对象
let o, d;
o = {
get foo() {
return 17;
},
};
d = Object.getOwnPropertyDescriptor(o, "foo");
console.log(d);
// {
// configurable: true,
// enumerable: true,
// get: [Function: get foo],
// set: undefined
// }
o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, "bar");
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 42,
// writable: true
// }
o = { [Symbol.for("baz")]: 73 };
d = Object.getOwnPropertyDescriptor(o, Symbol.for("baz"));
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 73,
// writable: true
// }
o = {};
Object.defineProperty(o, "qux", {
value: 8675309,
writable: false,
enumerable: false,
});
d = Object.getOwnPropertyDescriptor(o, "qux");
console.log(d);
// {
// value: 8675309,
// writable: false,
// enumerable: false,
// configurable: false
// }
非对象强制转换
会将非对象的第一个参数强制转换为对象
Object.getOwnPropertyDescriptor("foo", 0);
// Object returned by ES2015 code: {
// configurable: false,
// enumerable: true,
// value: "f",
// writable: false
// }
Object.getOwnPropertyDescriptors()
Object.getOwnPropertyDescriptors(obj) 静态方法返回给定对象的所有自有属性描述符。
浅拷贝一个对象
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
);
创建子类
function superclass() {}
superclass.prototype = {
// 在这里定义超类的构造方法、方法和属性
};
function subclass() {}
subclass.prototype = Object.create(superclass.prototype, {
// 在这里定义子类的构造方法、方法和属性
});