Object.getPrototypeOf()

1、作用

获取指定对象的原型(内部​​[[Prototype]]​​属性的值),如果没有继承属性,则返回 null 

      function Animal() {}
      var ani = new Animal();
      console.log(ani);
      console.log(Object.getPrototypeOf(ani));

 Object.getPrototypeOf()_第1张图片

2、注意 

在 ES5 中,如果传递给方法的参数不是对象,则会抛出TypeError异常;

在 ES6 中,如果传递给方法的参数不是对象,则会强制类型转换为对象。 

3、实际打印 

基本数据类型: 

      console.log(Object.getPrototypeOf("1") === String.prototype); // true
      console.log(Object.getPrototypeOf(1) === Number.prototype); // true
      console.log(Object.getPrototypeOf(true) === Boolean.prototype); // true
      console.log(Object.getPrototypeOf(Symbol()) === Symbol.prototype); // true
      console.log(Object.getPrototypeOf(null)); // 报错 Cannot convert undefined or null to object
      console.log(Object.getPrototypeOf(undefined)); // 报错 Cannot convert undefined or null to object
      console.log(Object.getPrototypeOf(BigInt(111)) === BigInt.prototype); // true

复杂数据类型: 

     console.log(Object.getPrototypeOf({}) === Object.prototype); // true

      console.log(Object.getPrototypeOf(Date) === Date.prototype); // false
      console.log(Object.getPrototypeOf(new Date()) === Date.prototype); // true
      console.log(Object.getPrototypeOf(Date()) === String.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

创建一个原型对象的对象: 

      // 创建一个没有原型对象的对象
      let obj1 = Object.create(null);
      console.log(Object.getPrototypeOf(obj1)); // null

      let proto = {};
      let obj2 = Object.create(proto);
      console.log(Object.getPrototypeOf(obj2) === proto); // true

你可能感兴趣的:(每日专栏,JavaScript,javascript,前端,开发语言)