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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理