JavaScript 对象的创建方式

本文深入探讨JavaScript中的多种构造模式,包括工厂模式、构造函数模式、原型模式及其混合使用方式。对比不同模式的特点,并通过示例代码展示如何创建对象实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值