【js】创建对象的6种基本方式

创建对象

  1. 字面量
  2. new Object()
  3. 工厂模式
  4. 构造函数
  5. 原型模式
  6. 构造函数+原型模式
1.字面量
let student = { name: "张三", age: 18, getName() { console.log(this.name); }, getAge() { console.log(this.age); } } console.log(student.name); //张三 student.getAge() //18

  • 在{}中添加属性与方法
  • 可以使用.追加属性与方法
  • 创建类似的对象,会出现大量重复代码
2.new Object()
let student = new Object(); student.name = "张三" student.age = 18 student.getName = function () { console.log(this.name); } student.getAge = function () { console.log(this.age); } console.log(student.name); //张三 student.getAge()//18

  • 实例化内置对象后再追加属性与方法
  • 创建类似的对象,会有大量的代码重复
3.工厂模式
function creatStudent(name, age) { let student = new Object() student.name = name student.age = age student.getName = function () { console.log(this.name); } student.getAge = function () { console.log(this.age); } return student } let std1 = creatStudent("张三", 18) let std2 = creatStudent("李四", 20) std1.getName() //张三 std2.getAge()//20

  • 将new Object()实例化对象然后赋值的方式 写在函数里,将不同的值以参数的形式传入
  • 创建类似的对象只需要传入不同的参数,减少代码量
  • 不能确定是什么种类的对象,使用instanceof只能判断是否是对象
4.构造函数
function Student(name, age) { this.name = name this.age = age this.getName = function () { console.log(this.name); } this.getAge = function () { console.log(this.age); } } let std1 = new Student("张三", 18) let std2 = new Student("李四", 20) std1.getAge()//18 console.log(std2 instanceof Student); //true console.log(std1.getName == std2.getName); //false

  • 使用new改变构造函数的this指向,创建新对象
  • 可以通过instanceof判断对象种类
  • 相同的方法不能共用,创建重复的方法,影响性能
5.原型模式
function Student() { } Student.prototype.name = "张三" Student.prototype.age = 18 Student.prototype.getName = function () { console.log(this.name); } Student.prototype.getAge = function () { console.log(this.age); } let std1 = new Student() let std2 = new Student() std2.name = "李四" std2.age = 20 std1.getName() //张三 std2.getAge()//20 console.log(std1.getAge == std2.getAge); //true

  • 共享属性与方法,可以给对象设置自己的方法
  • 不会重建相同的方法
6.构造函数+原型模式
function Student(name, age) { this.name = name this.age = age } Student.prototype = { constructor: Student, getName() { console.log(this.name); }, getAge() { console.log(this.age); } } let std1 = new Student("张三", 18) let std2 = new Student("李四", 20) std1.getName()//张三 std2.getAge() //20 console.log(std1.getAge == std2.getAge); //true

  • 非共享的属性或方法采用构造函数或单独追加的方式
  • 共享的属性与方法使用原型模式

    推荐阅读