JS new关键字做了什么

227 阅读1分钟

面向对象中关键字new

  • 创建类实例 对象
  • 创建实例时执行构造函数
class Son{
    constructor(name,age){
        this.name=name
        this.age=age
    }
    say(){
        console.log(`My name is ${this.name} age ${this.age}`)
    }
}

const son=new Son('李四',22)

son.say()
function Person(name,age){
    this.name=name
    this.age=age
}

Person.prototype.say=function(){
    console.log(`My name is ${this.name} age ${this.age}`)
}

const person =new Person('张三',18)

person.say()

new的作用分析及实现

function myNew(fn,...args){
    //创建一个空对象
    const obj={}
    //将该对象的__proto__属性链接到构造函数原型对象
    obj.__proto__=fn.prototype
    //将该对象作为this上下文调用构造函数并且返回新对象
    const res=fn.apply(obj,args)
    //如果返回值存在并且是引用数据类型,返回构造函数返回值,否则返回创建的对象
    return typeof res ==='object' ? res :obj
}

const persons=myNew(Person,'王五',30)

persons.say()