关于javascript:js创建对象的6种基本方式

4次阅读

共计 1967 个字符,预计需要花费 5 分钟才能阅读完成。

创建对象

  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
  • 非共享的属性或办法采纳构造函数或独自追加的形式
  • 共享的属性与办法应用原型模式
正文完
 0