Object.getPrototypeOf(object)
这个还蛮简单的,返回给定对象的原型。如果没有继承属性,则返回 null
在ES5中,如果传递给方法的参数不是对象,则会抛出TypeError异常。
在ES6中,如果传递给方法的参数不是对象,则会强制类型转换为对象。
基本用法:
var a = '你好'
console.log(Object.getPrototypeOf(a) === String.prototype) // true
var b = 5
console.log(Object.getPrototypeOf(b) === Number.prototype) // true
var c = false
console.log(Object.getPrototypeOf(c) === Boolean.prototype) // true
var d = {}
console.log(Object.getPrototypeOf(d) === Object.prototype) // true
var e = null
console.log(Object.getPrototypeOf(e)) // TypeError: Cannot convert undefined or null to object
var f = undefined
console.log(Object.getPrototypeOf(f)) // TypeError: Cannot convert undefined or null to object
var g = Symbol('g');
Object.getPrototypeOf(g) === Symbol.prototype; // true
// 创建一个没有原型对象的对象
var obj = Object.create(null);
Object.getPrototypeOf(obj); // null
console.log(Object.getPrototypeOf(Date) === Date.prototype) // false
console.log(Object.getPrototypeOf(Date()) === String.prototype) // true
console.log(Object.getPrototypeOf(new Date()) === Date.prototype) // true
console.log(Object.getPrototypeOf(Function) === Function.prototype) // true
console.log(Object.getPrototypeOf(Function()) === Function.prototype) // true
console.log(Object.getPrototypeOf(new Function()) === Function.prototype) // true
console.log(Object.getPrototypeOf(Object()) === Object.prototype) // true
console.log(Object.getPrototypeOf(Object) === Function.prototype) // true
console.log(Object.getPrototypeOf(new Object()) === Object.prototype) // true
console.log(Object.getPrototypeOf({}) === Object.prototype) // true
console.log({} == new Object()) // false