【js】创建对象的6种基本方式
创建对象
- 字面量
- new Object()
- 工厂模式
- 构造函数
- 原型模式
- 构造函数+原型模式
let student = {
name: "张三",
age: 18,
getName() {
console.log(this.name);
},
getAge() {
console.log(this.age);
}
}
console.log(student.name);
//张三
student.getAge() //18
- 在{}中添加属性与方法
- 可以使用
.
追加属性与方法 - 创建
类似
的对象,会出现大量重复代码
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
- 实例化
内置对象
后再追加属性与方法 - 创建
类似
的对象,会有大量的代码重复
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只能判断是否是对象
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判断对象种类
- 相同的方法不能共用,创建重复的方法,影响性能
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
- 共享属性与方法,可以给对象设置自己的方法
- 不会重建相同的方法
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
- 非共享的属性或方法采用构造函数或单独追加的方式
- 共享的属性与方法使用原型模式
推荐阅读
- 宽容谁
- 我要做大厨
- 增长黑客的海盗法则
- 画画吗()
- 2019-02-13——今天谈梦想()
- 远去的风筝
- 三十年后的广场舞大爷
- 叙述作文
- 20190302|20190302 复盘翻盘
- 学无止境,人生还很长