根据JS原型链机制,可以通过Object.prototype获取Object的原型对象,这个对象也是原型链的终极原型(最外层的原型),
但是发现console.info(Object.prototype)为空,看不到定义的toString等原型属性,感觉很意外。
正确方法:
1、可以使用 Object.getOwnPropertyNames(Object.prototype) 获取对象的所有属性。
[ 'constructor',
'__defineGetter__',
'__defineSetter__',
'hasOwnProperty',
'__lookupGetter__',
'__lookupSetter__',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'valueOf',
'__proto__',
'toLocaleString' ]
2、使用Object.getOwnPropertyDescriptor(Object.prototype,'toString') 获取对象某个属性的描述符。
{ value: [Function: toString],
writable: true,
enumerable: false,
configurable: true }
重点:这里发现enumerable属性为false,即Object原型的属性是不可遍历的,这也是为什么直接使用console.info(Object.prototype)获取的为{}的原型。
测试如下:
// 定义属性一 Object.prototype.testString = function () { console.info('object prototype testString') } //定义属性二 Object.defineProperty(Object.prototype, "testString2", { configurable: true, enumerable: false, writable: true, value: function () { console.info('aaaa') } }) console.info(Object.prototype) 输出:{ testString: [Function] }
这里发现也只有一个属性,然后把属性二的enumerable改为true,发现是可以打印的。