Object 对象的相关方法数组
var F = function () {}; var f = new F(); Object.getPrototypeOf(f) === F.prototype // true
// 空对象的原型是 Object.prototype Object.getPrototypeOf({}) === Object.prototype // true // Object.prototype 的原型是 null Object.getPrototypeOf(Object.prototype) === null // true // 函数的原型是 Function.prototype function f() {} Object.getPrototypeOf(f) === Function.prototype // true
var a = {}; var b = {x: 1}; Object.setPrototypeOf(a, b); Object.getPrototypeOf(a) === b // true a.x // 1
将对象 a 的原型,设置为对象 b,所以 a 能够共享 b 的属性浏览器
var F = function () { this.foo = 'bar'; }; var f = new F(); // 等同于 var f = Object.setPrototypeOf({}, F.prototype); // 将一个空对象的原型设为构造函数的prototype属性 F.call(f); // 将构造函数内部的this绑定这个空对象,而后执行构造函数,使得定义在this上面的方法和属性(上例是this.foo),都转移到这个空对象上
// 原型对象 var A = { print: function () { console.log('hello'); } }; // 实例对象 var B = Object.create(A); Object.getPrototypeOf(B) === A // true B.print() // hello B.print === A.print // true
以 A 对象为原型,生成了 B 对象。B 继承了 A 的全部属性和方法函数
var obj = Object.create({}, { p1: { value: 123, enumerable: true, configurable: true, writable: true, }, p2: { value: 'abc', enumerable: true, configurable: true, writable: true, } }); // 等同于 var obj = Object.create({}); obj.p1 = 123; obj.p2 = 'abc';
function A() {} var a = new A(); var b = Object.create(a); b.constructor === A // true b instanceof A // true
上面代码中,b 对象的原型是 a 对象,所以继承了 a 对象的构造函数this
var o1 = {}; var o2 = Object.create(o1); var o3 = Object.create(o2); o2.isPrototypeOf(o3); // true o1.isPrototypeOf(o3); // true
var P = function () {}; var p = new P(); var C = function () {}; C.prototype = p; C.prototype.constructor = C; var c = new C(); c.constructor.prototype === p // true
'length' in Date // true 'toString' in Date // true
var o1 = { p1: 123 }; var o2 = Object.create(o1, { p2: { value: "abc", enumerable: true } }); for (p in o2) { console.info(p); } // p2 自身的属性 // p1 继承的属性
为了得到对象自身的属性,能够采用hasOwnProperty方法判断一下spa
for ( var name in object ) { if ( object.hasOwnProperty(name) ) { console.log(name); } }
function inheritedPropertyNames(obj) { var props = {}; while(obj) { Object.getOwnPropertyNames(obj).forEach(function(p) { props[p] = true; }); obj = Object.getPrototypeOf(obj); // 原型对象的原型对象 } return Object.getOwnPropertyNames(props); }
inheritedPropertyNames(Date);
// [
// "caller",
// "constructor",
// "toString",
// "UTC",
// ...
// ]prototype
function copyOwnPropertiesFrom(new, old) { Object.getOwnPropertyNames(old).forEach(function (propKey) { var desc = Object.getOwnPropertyDescriptor(old, propKey); Object.defineProperty(new, propKey, desc); }); return new; } function copyObject(old) { var new = Object.create(Object.getPrototypeOf(old)); copyOwnPropertiesFrom(new, old); return new; }
function copyObject(orig) { return Object.create( Object.getPrototypeOf(orig), Object.getOwnPropertyDescriptors(orig) ); }