创建对象的方式有
- 直接创建对象
- 工厂函数创建对象
- 构造函数创建对象
- 使用原型优化构造函数
一、使用直接创建对象
代码:
var student1={
name:"张三",
age:18,
eat:function(){
console.log(this.name+"能吃饭")
},
run:function(){
console.log(this.name+"能跑步")
}
}
console.log(student1)
student1.run();
student1.eat();
总结:优点:创建方便,缺点:如果需要创建多个需要写很多重复的代码
二、工厂函数创建对象
直接创建多个对象有很多重复的代码,可以用函数快速创建多个对象
代码:
function students(name,age){
var obj=new Object();
obj.name=name;
obj.age=age;
obj.eat=function(){
console.log(this.name+"会吃饭")
}
obj.run=function(){
console.log(this.name+"能跑步")
}
return obj
}
var student1=students("张三",18);
var student2=students("李四",20);
console.log(student1)
student1.run()
student1.eat()
console.log(student2)
student2.run()
student2.eat()
总结 优点:创建多个对象方便
缺点:在创建多个种类的对象的时候(比如老师对象和学生对象)进行instanceof判断指定数据类型的时候无法分辨区别,会出现问题。
三、构造函数创建对象
为了解决工厂函数无法分辨执行类型的问题,并且参考了其他强编程语言的类的特点。
创建原理通过this的指向的改变来完成对象的创建
代码:
function Student(name,age){
this.name=name;
this.age=age;
this.eat=function(){
console.log(this.name+"能吃饭")
}
}
function Teacher(name,age){
this.name=name;
this.age=age;
this.eat=function(){
console.log(this.name+"能吃饭")
}
}
var student=new Student("张三",18);
var teacher=new Teacher("李四",19);
console.log(student);
student.eat()
console.log(teacher)
teacher.eat()
console.log(student instanceof Student)
console.log(student instanceof Teacher)
发现可以使用instanceof判断类型,但是在创建的时候每次都是重新生成一个对象,很多重复的属性没有用上,会占用很多多余的内存
function Student(name,age){
this.name=name;
this.age=age;
this.eat=function(){
console.log(this.name+"能吃饭")
}
}
var student=new Student("张三",18);
var student2=new Student("李四",18);
console.log(student.eat==student2.eat)
输出的值为false,说明这两个属性的内存指向不同,
但是代码没有区别
总结:优点:能批量创建,能判断具体类型。缺点:重复的代码还占用内存,内存消耗过大
四、使用原型优化构造函数创建
由于内存消耗的问题,所以我们把共有的一些方法写到原型上,这样实例化的对象也可以直接使用
代码:
function Student(name,age){
this.name=name;
this.age=age;
}
Student.prototype.eat=function(){
console.log(this.name+"能吃饭")
}
var student=new Student("张三",18);
student.__proto__.run=function(){
console.log(this.name+"能跑")
}
var student2=new Student("李四",18);
console.log(student)
student.eat();
student.run();
console.log(student2)
student.run();
console.log(student.eat==student2.eat)
由于构造函数的prototype和实例化的__proto__指向的是同一个地方,所以使用这两种都能完成添加新方法的创建