学习笔记——proto和prototype

49 阅读1分钟

1.proto

  1. 该属性在MDN官网现在已经不被推荐使用,我们可以使用Object.getPrototypeOf()来获取该属性的值。

  1. 该值存储的是一个构造函数的prototype ,该构造函数的prototype又会有一个__proto__,直到最后该__proto__指向Object.prototype

  2. 该属性在创建变量或者函数的时候,会将该值指向对应的变量构造函数

  3. 访问__proto__其实就是在找原型链,绝大多数的变量都有原型链,且原型链终端指向Object.prototype,但是undefind和null是没有的,object.create(null)创建出来的对象也是没有的

  4. 该属性不能手动的添加,就算添加上了,也是没办法找原型链的

let nulls = null
Object.getPrototypeOf(nulls) //会报错

let undefineds = undefined
Object.getPrototypeOf(undefined) //会报错

let a = 'abc'
Object.getPrototypeOf(a) === String.prototype //true
Object.getPrototypeOf(String.prototype) === Object.prototype //true

let b = 123
Object.getPrototypeOf( b) === Number.prototype //true
Object.getPrototypeOf(Number.prototype) === Object.prototype //true

let c = function() {}
Object.getPrototypeOf(c) === Function.prototype //true
Object.getPrototypeOf(Function.prototype) === Object.prototype //true

let d =  {}
Object.getPrototypeOf(d) === Object.prototype //true
//Object.getPrototypeOf(Object.prototype)这个值已经到了顶端,为null了
Object.getPrototypeOf(Object.prototype) === Object.prototype //false

let e = []
Object.getPrototypeOf(e) === Array.prototype //true
Object.getPrototypeOf(Array.prototype) === Object.prototype //true

let f = true
Object.getPrototypeOf(f) === Boolean.prototype //true
Object.getPrototypeOf(Boolean.prototype) === Object.prototype //true

2.prototype

  1. 该属性通常出现在构造函数上,但并不是所有拥有该属性的函数都能被叫做构造函数,如生成器函数。
  2. 一些函数,它们并没有prototype属性,如箭头函数。
  3. 默认情况下,函数的 prototype 是一个普通的对象。这个对象具有一个属性:constructor。它是对这个函数本身的一个引用。 constructor 属性是可编辑、可配置但不可枚举的。
  4. prototype和__proto__本质上来说,他们之间是没有关系的,只是构造函数生成的对象的 __proto__会等于该构造函数的prototype
function Person() {}
var person = new Person()
person.__proto__ === Person.prototype //true