JavaScript 对象的创建方式

JavaScript中所有对象来自于Object

工厂模式

坏处:无法判断返回的对象是什么类型

function people(name,age,work){
  var man= new Object();
      man.name=name;
      man.age=age;
      man.work=work;
      man.getMan=function(){
        alert(this.name);
      }
      return man;
}
  var people1 = people('Tom',18,'student');
构造函数模式
与工厂模式相比:没有return语句 可以识别对象类型 没有显示创建对象 直接指向this对象

function People(name,age,work){ //注意第一个首字母大写
  this.name=name;
  this.age=age;
  this.work=work;
  this.getName=function(){
    console.log(this.name);
  }
}
var people1= new People('jerry',20,'student');

原型模式

Object.prototype.constructor 特定的函数,用于创建一个对象的原型

function People(){

};
People.prototype.name='Lily';
People.prototype.age=18;
People.prototype.work='singer';
People.prototype.getPeople=function(){
  console.log(this.name);
}
  var people1=new People();
  console.log(people1.name); //Lily
  var people2=new People();
  console.log(people2.name); //Lily

prototype属性,是一个指针指向一个对象

当构造一个对象(people1)后,他的默认属性name就是Lily。

混合模式

混合模式就是原型加上构造函数

function People(name,age,work){
  this.name=name;
  this.age=age;
  this.work=work;
}
People.prototype={
  constructor: People,
  getName:function(){
    console.log(this.name);
  }
}
var people1= new People('Lily',18,'student');
console.log(people1);  //{name: "Lily", age: 18, work: "student"}

最大限度的节省了内存 构造函数用于定义属性 原型用于定义和共享

动态原型模式

将所有信息封装在构造函数内 而通过构造函数中初始化原型

  function People(name,age){
    this.name=name;
    this.age=age;
    if(typeof this.human!="function"){
      console.log('Tom');
      People.prototype.human=function(){
        console.log('名字'+this.name+'年龄'+this.age);
      }
    }
  }
  var people1= new People('Lily',18);
  //console.log Tom

猜你喜欢

转载自blog.csdn.net/onion_line/article/details/79499019