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) ); }