JavaScript创建对象常用模式

本文详细介绍了JavaScript中四种常见的对象创建模式:工厂模式、构造函数模式、原型模式以及组合使用构造函数和原型模式。每种模式的特点、优势与问题都进行了阐述,例如工厂模式的对象识别问题、构造函数模式的方法共享问题等,并展示了如何通过组合模式解决这些问题。同时,文中还探讨了不同模式下对象属性和方法的共享与识别情况。

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

1. 工厂模式

function student(name, age) {
  let o = new Object()
  o.name = name
  o.age = age
  o.show = function(){
    console.log(`我叫${this.name}`)
  }
  return o
}

let a = student('小明', 18)
let b = student('小红', 20)

工厂模式的问题

工厂模式存在对象识别的问题,因为变量a与b是Object的实例,并不是student的实例,如:

console.log(a instanceof Object) // true
console.log(a instanceof student) // false

2. 构造函数模式

function Student(name, age) {
  this.name = name
  this.age = age
  this.show = function() {
    console.log(`我叫${this.name}`)
  }
}

let a = new Student('小明', 18)
let b = new Student('小红', 20)

构造函数首字母大写

注意构造函数Student首字母大写了,这样方便用于区分构造函数和普通函数。

构造函数模式与工厂模式的区别

构造函数模式与工厂模式对比,构造函数中没有return,没有显性的创建对象,属性和方法赋值给了this,并且创建实例需要使用new操作符。

构造函数模式能正确识别对象

因为a和b都是Student的实例,所以它能正确的识别对象,如:

console.log(a instanceof Student) // true

构造函数模式的问题

构造函数模式也有问题,它的方法会在每个实例上都创建一遍,如前面的代码,a和b都有一个show方法,但是他们不是同一个Function实例:

console.log(a.show === b.show) // false

为了解决这个问题,需要把函数放在构造函数外部,如:

function show() {
	console.log(`我叫${this.name}`)
}
function Student(name, age) {
  this.name = name
  this.age = age
  this.show = show
}

let a = new Student('小明', 18)
let b = new Student('小红', 20)
console.log(a.show === b.show) // true

3. 原型模式

function Student() {}
Student.prototype.name = '小明'
Student.prototype.age = 18
Student.prototype.show = function() { console.log(`我叫${this.name}`) }

let a = new Student()
let b = new Student()
a.show() // 我叫小明
b.show() // 我叫小明

使用原型模式的好处是它原型对象(prototype)中的属性和方法会在实例上共享。

console.log(a.name === b.name) // true
console.log(a.show === b.show) // true

原型模式的问题

原型模式没有初始化传参的这个步骤,这样会带来很大的不方便。

4. 组合使用构造函数模式和原型模式

这是最常见的方式,既能解决原型模型不能传参的问题,又能解决构造函数模式方法不共享的问题。

function Student(name, age) {
  this.name = name
  this.age = age
}
Student.prototype = {
	constructor : Student, 
	show: function(){ 
		console.log(`我叫${this.name}`)
	}
}
let a = new Student('小明', 18)
let b = new Student('小红', 20)
a.show() // 我叫小明
b.show() // 我叫小红
console.log(a.show === b.show) // true
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吴佩佩佩佩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值