面向对象中关键字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={}
obj.__proto__=fn.prototype
const res=fn.apply(obj,args)
return typeof res ==='object' ? res :obj
}
const persons=myNew(Person,'王五',30)
persons.say()