JS 原型对象与原型链

108 阅读1分钟

一、prototype 原型对象

1、定义||作用

  • 每个函数都有对应的原型
  • 给其它对象提供共享属性的对象

2、语法

function fn() {}
fn.prototype.xxx = 'xxx'
const obj = new fn()
console.log(obj.xxx) // xxx

二、proto 原型链

1、定义||作用

  • 通过原型链访问到上级原型对象

2、语法

function fn() {}
const obj1 = new fn()
const obj2 = new fn()
obj1.__proto__.xxx = 'xxx'
console.log(obj2.xxx) // xxx

3、原型链图解

graph BT
A(["第四级:null"])
B(["第三极:Object.prototype"])
C(["第二级:fn.prototype"])
D(["第一级:new fn()"])
D--.__proto__-->C--.__proto__-->B--.__proto__-->A

三、constructor

1、定义||作用

  • 返回 Object 的构造函数

2、语法

function fn() {}
const obj1 = new fn()
console.log(obj1.constructor === fn) // true

四、三者关系

1、简单图示

2、详细图示

graph TD
A(["obj"])
B{{"函数fn"}}
C(["fn的原型对象"])
D{{"Function"}}
E(["Function的原型对象"])
F{{"Object"}}
G(["Object的原型对象"])
H{{"null"}}
B--new-->A
A==.__proto__==>C
B==.__proto__===>E
B-..prototype.->C
C==.__proto__==>G
C--.constructor--->B
D==.__proto__===>E
D-..prototype.->E
E==.__proto__==>G
F==.__proto__===>E
F-..prototype.->G
F--.constructor-->D
G==.__proto__==>H

3、代码演示

function fn() {}
const obj = new fn()

console.log(obj.__proto__ === fn.prototype)
console.log(fn.__proto__ === Function.prototype)
console.log(fn.prototype.__proto__ === Object.prototype)
console.log(fn.prototype.constructor === fn)
console.log(Function.__proto__ === Function.prototype)
console.log(Function.prototype.__proto__ === Object.prototype)
console.log(Object.__proto__ === Function.prototype)
console.log(Object.prototype.__proto__ === null)
console.log(Object.constructor === Function)
// 结果都为true