四种创建对象方式及优缺点

163 阅读1分钟

1.直接创建对象

let student={
   name:'百川'
   age:21,
   height:180
}

优点:简单 

缺点:无法进行相同对象量产

2.工厂模式(通过封装函数,来创建指定的对象)

function createStudent(name,age,height){
    var obj={}
    obj.name=name
    obj.age=age
    obj.height=height
    obj.showInfo=function(){
      console.log(this.name)  
  }
    return obj
}

优点:快速进行相同类型对象的量产

缺点:无法明确,确定的类型

3.构造函数

js没有类,利用构造函数模拟类,核心思想:改变this的指向性

function Student(name,age,height){
    this.name=name
    this.age=age
    this.showInfo=function(){
       console.log(this.name) 
  }
}
 
 let s1=new Student('百川',18,180)
 console.log(s1)

new做了什么?

  1. 创建一个空对象{}

  2. 执行后方函数,让函数内部this指向 空对象{}

  3. 将创建出来的对象返回

优点:量产,又能检测对应的类型

缺点:相同的方法,没有开辟共同的空间,导致内存消耗

4.原型创建对象

将构造函数中的方法,定义到原型中

function Student(name,age,height){
   this.name=name
   this.age=age
   this.height=height
}
 
Student.prototype.showInfo=function(){
    console.log(this.name)
}
 
let s1=new Student('百川',18,180)
 
let s2=new Student('张三',23,180)
 
console.log(s1.showInfo==s2.showInfo)

构造函数的原型(prototype)== 实例化对象的原型(proto

通过相同构造函数创建出来的对象 原型相同

优点:量产,可以判断类型,节约内存