js创建对象的几种方式

十度 javaScript 2016年02月23日 收藏

一、工厂模式

  1. function createStudent(name,age){
  2. var o=new Object();
  3. o.name=name;
  4. o.age=age;
  5. o.myName=function(){
  6. alert(this.name);
  7. };
  8. return o;
  9. }
  10. var student1 =createStudent('yjj',15);
  11. var student2 = createStudent('fff',18);
  12. //问题: 工厂模式没有解决对象识别的问题,不能确定一个对象的类型

二、构造函数模式

  1. function Student(name,age){
  2. this.name=name;
  3. this.age=age;
  4. this.myName=function(){
  5. alert(this.name);
  6. };
  7. }
  8. var student1_ = new Student('yjj',15);
  9. var student2_ = new Student('fff',18);
  10. //new 关键字的作用
  11. //1.创建一个对象
  12. //2.将构造函数的作用域赋给新对象,this指向了新对象
  13. //3.执行构造函数中的代码,为新对象添加熟悉
  14. //4.返回新对象
  15. //问题: 每个方法都要在每个实例上重新创建一遍

三、构造函数模式+原型模式

  1. function Student(name,age){
  2. this.name=name;
  3. this.age=age;
  4. }
  5. Student.prototype.myName=function(){
  6. alert(this.name);
  7. };
  8. var student1__ = new Student('yjj',15);
  9. var student2__ = new Student('fff',18);
  10. student1__.myName();

四、动态原型模式

  1. function Student(name,age){
  2. this.name=name;
  3. this.age=age;
  4. if(typeof this.myName!="function"){//第一次进入
  5. Student.prototype.myName=function(){
  6. alert(this.name);
  7. };
  8. }
  9. }
  10. var student1___ = new Student('yjj',15);
  11. student1___.myName();

五、寄生构造函数模式

  1. function Student(name,age){
  2. var o = new Object();
  3. o.name=name;
  4. o.age=age;
  5. o.myName=function(){
  6. alert(this.name);
  7. };
  8. return o;
  9. }
  10. var student1____ = new Student('yjj',15);
  11. student1____.myName();
  12. //这种模式的基本思想是创建一个函数,该函数的作用仅仅是封装创建对象的代码,然后再返回新创建的对象。

六、稳妥构造函数模式

  1. function Student(name,age){
  2. var o = new Object();
  3. var name=name;
  4. var age=age;
  5. o.myName=function(){
  6. alert(name);
  7. };
  8. return o;
  9. }
  10. var student1_____ = new Student('yjj',15);
  11. student1_____.myName();
  12. //没有公共属性,而且其他方法也不用引用this的对象