**1.字面量创建**
var obj = { }
var obj = {
name : "jack",
age : 16,
score:100
}
缺点 : 一次只能创建一个,多个同类对象创建时 代码会重复
2、使用 工厂模式 创建对象 (设计模式之--工厂模式)
通过函数调用来创建对象的,因此存在缺陷。
优点 : 解决多个同类对象创建时代码重复问题
缺点 : 对象是通过函数调用的方式创建的 创建对象的方式不规范
不能确定某个对象属于哪一个类(构造函数)
案例1
//第一步 创建一个工厂
function studentInfo(name,tel){
//第二步 备料--创建一个对象
var obj = new Object();
obj.name = name;
obj.tel = tel;
// 出厂--返回对象
return obj;
}
//创建对象 通过函数调用
var stu1 = studentInfo("小张","12312241251");
var stu2 = studentInfo("小王","12312241253");
console.log( stu1.name , stu2.name );
案例2
function animalInfo(name,color){
var obj = new Object();
obj.name = name;
obj.color = color;
return obj;
}
var a1 = animalInfo("小白","white");
var a2 = animalInfo("小黑","black");
//判断一个对象属于哪一个构造函数 instanceof
console.log(a1 instanceof Object);
console.log(a2.instanceof Object);
3、使用 构造函数 创建对象
构造函数命名一般是大驼峰格式,为了和普通函数进行区分
构造函数中的属性称为实例属性 构造函数中的方法称为实例方法
构造函数中的this指向 构造函数new出来的对象
优点 :对象使用new关键字创建的 创建对象的方式规范
能够确定某个对象属于哪一个类 instanceof
缺点 : 多个同类对象的方法会被重复创建 空间不共享
案例1
function Student(){
//实例属性
this.name = name;
this.tel = tel;
//实例方法
this.study = function(){
return this.name + "在学习"
}
}
var stu1 = new Student("jack","12345678956");
var stu2 = new Student("lily","12345678986");
console.log(stu1.stydy());
console.log(stu2.stydy());
案例2
function Animal(name,color){
this.name = name;
this.color = color;
this.running = function(){
return "奔跑";
}
}
var a1 = new Animal("大白","white");
var a2 = new Animal("小白","white");
console.log(a1 instanceof Animal);
console.log(a2 instamceof Animal);
console.log(a1.running == a2.running)
4、使用 构造函数 创建对象 方法和属性都是原型属性和原型方法 关键字prototype
优点 : 使用原型方法 能够解决多个同类对象创建时 空间不共享问题 原型方法空间共享
function Student(){
}
//原型的属性
Student.prototype.name = "jack";
Student.prototype.age = 18;
//原型方法
Student.prototype .study = function(){
return this.name + "在学习";
}
var stu1 = new Student();
var stu2 = new Student();
console.log(stu1.name,stu1.age,stu1.study());
console.log(stu2.name,stu2.age,stu2.study());
console.log(stu1.study == stu2.study)
5、混合 方式 创建对象
属性写在构造函数的内部 作为实例属性
方法写在构造函数的外部 作为原型方法
案例1 构建函数和原型创造函数方法的混合 完美的创建对象的方法
function Student(name,age){
//把属性放在里面 构建函数方法
this.name = name;
this.age = age;
}
//方法放在外面 原型创造函数方法
Student.prototype.study = function(){
return this.name + "在学习";
}
var stu1 = new Student("jack",17);
var stu2 = new Student("lily",18);
console.log(stu1.name,stu1.age,stu1.study());
console.log(stu2.name,stu2.age,stu2.study());
console.log(stu1.study == stu2.study)//study没带括号输出的是整个函数