JS中的绊脚石-原型链

96 阅读2分钟

1.基本概念

1.函数

函数定义

function myfun(name) { //函数声明
    console.log("函数:",name)
}
let myfun2 = function (name) { //函数表达式
    console.log("函数:",name)
}

let myfun3 =  (name)  =>{//函数表达式
    console.log("函数:",name)
}

2.Function 对象

Function 对象是全局对象,可以动态创建函数,实际上每个函数都是一个 Function 对象。

上面的代码 等价于new Function的写法

let myfun = new Function ('name','console.log(`函数:${name}`)')
let myfun2 = new Function ('name','console.log(`函数:${name}`)') 
let myfun3 = new Function ('name','console.log(`函数:${name}`)')

3.构造函数

  1. 能使用new 创建的函数就是构造函数
  2. 箭头函数不能new
function MyFun(name) {
    this.name = name
}
let myfun1 = new MyFun("方法1")
let myfun2 = new MyFun("方法2")
  1. 上面MyFun就是构造函数

4.是实例

如上图 myfun1,myfun2都是MyFun的实例,也可以叫对象

2.原型对象

1.prototype和__proto__

  1. 构造函数的 prototype 指向 原型对象 (显式原型)
  2. 实例的 proto 指向 原型对象 (隐式原型) 即
function MyFun(name) {
    this.name = name
}
let myfun1 = new MyFun("方法1")
let myfun2 = new MyFun("方法2")
MyFun.prototype === myfun1.__proto__ //为ture
MyFun.prototype === myfun2.__proto__ //为ture

image.png

2.Function是函数的原型对象

由于函数 等价于new Function

function myfun(name) { //函数声明
    console.log("函数:",name)
}
let myfun2 = function (name) { //函数表达式
    console.log("函数:",name)
}

let myfun3 =  (name)  =>{//函数表达式
    console.log("函数:",name)
}
myfun.__proto__ === Function.proptotype //true
myfun2.__proto__ === Function.proptotype //true
myfun3.__proto__ === Function.proptotype //true

image.png

3.对象

创建的4种方式:

function User(name) {//构造函数
    this.name = name
}
const user1 = new User("jason")

const user2 = {name : 'jason'} //字面量创建

const user3 = new Object() //使用对象创建 与上面字面量创建是等价的
user3.name = 'jason'

const user4 = Object.create({}) //默认创建是空原型对象
user4.name = 'jason'

由于最终user2和user3都是Object对象创建,所以user.proto === Object.prototype

console.log(  user1.__proto__ === User.prototype)//true 指向User
console.log(  user2.__proto__ === Object.prototype)//true 指向Object
console.log(  user3.__proto__ === Object.prototype)//true 指向Object
console.log(  user4.__proto__ === Object.prototype) //false 指向Object,但是对象原型是{},不是Object

image.png

4.Object与Function关系

  1. function Object()也是个函数,也是Function构造函数的实例
  2. function Function()也是函数,也是Function构造函数的实例,同时也是自己本身的实例

image.png

5.constructor构造函数

原型对象的constructor === 对象的构造函数。

可以理解通过原型对象的constructor 反向找构造函数。

function User(name) {//构造函数
    this.name = name
}

User.prototype.constructor === User //true 

image.png

6.原型对象关联

  • User.prototype 也是对象
  • Function.prototype 也是对象 都是实例,都指向Object.prototype
function User(name) {//构造函数
    this.name = name
} 
console.log(User.prototype.__proto__ === Object.prototype) // true
console.log(Function.prototype.__proto__ === Object.prototype) // true

7.找到原型的终点

Object.prototype的__proto__ 是null image.png

8.打印原型信息

function getPrototypeChain(obj){
    let list = [];
    while(obj = Object.getPrototypeOf(obj)){
        list.push(obj)
    }
    list.push(null)
    return list
}