创建对象
- 字面量
- new Object()
- 工厂模式
- 构造函数
- 原型模式
- 构造函数+原型模式
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 = 18student.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()//18console.log(std2 instanceof Student);//trueconsole.log(std1.getName == std2.getName);//false
- 应用new扭转构造函数的this指向,创立新对象
- 能够通过instanceof判断对象品种
- 雷同的办法不能共用,创立反复的办法,影响性能
5.原型模式
function Student() { }Student.prototype.name = "张三"Student.prototype.age = 18Student.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 = 20std1.getName() //张三std2.getAge() //20console.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() //20console.log(std1.getAge == std2.getAge);//true
- 非共享的属性或办法采纳构造函数或独自追加的形式
- 共享的属性与办法应用原型模式