js构造函数
构造函数是批量创建相似对象的常见方式。
#type / concept
#status / growing
#resource / javascript
#resource / ecmascript
[!info] related notes
- 所属 MOC: ecmascript-object-oriented, ecmascript-prototypes
- 前置概念: js原型和原型链
- 并列概念: js-new, proto-prototype-constructor
- 关系笔记: ecmascript-object-oriented, ecmascript-prototypes
js构造函数
构造函数是批量创建相似对象的常见方式。
一句话定义
构造函数是 JavaScript 中一种配合 new 运算符使用、用于批量创建对象的特殊函数。它通过 this 关键字挂载实例属性,通过 prototype 挂载共享方法。
核心机制
构造函数和普通函数有什么区别
构造函数本质上就是函数,没有语法上的特殊标记。唯一的区别在于调用方式:
// 普通调用
function fn() {}
fn()
// 构造函数调用(配合 new)
function Person() {}
new Person()
当使用 new 调用时,函数会经历一个内部构造过程,返回一个对象实例。
为什么需要构造函数
JavaScript 在 ES6 class 语法出现之前,主要通过构造函数实现对象的批量创建:
function Person(name, age) {
this.name = name
this.age = age
}
const p1 = new Person('Tom', 20)
const p2 = new Person('Jerry', 25)
这样每创建一个实例,都会获得独立的 name 和 age 属性。
实例方法的两种写法
// 1. 在构造函数内定义(每个实例都有独立的方法)
function Person(name) {
this.name = name
this.say = function() {
console.log('Hello')
}
}
// 2. 在 prototype 上定义(所有实例共享方法)
function Person(name) {
this.name = name
}
Person.prototype.say = function() {
console.log('Hello')
}
写法 2 是更推荐的方式,避免每个实例都创建独立的函数对象,节省内存。
最小例子
function Point(x, y) {
this.x = x
this.y = y
}
const p1 = new Point(1, 2)
console.log(p1.x) // 1
console.log(p1.y) // 2
常见误解或边界
- 构造函数不一定要首字母大写 — 这只是约定,便于区分
new Foo()和foo() - 构造函数没有返回值时,默认返回
this— 即新创建的实例对象 - 如果构造函数手动返回对象,以返回的对象为准 — 忽略
this
function Test() {
this.value = 1
return { value: 2 } // 显式返回对象
}
new Test().value // 2
- 箭头函数不能作为构造函数 — 因为箭头函数没有
[[Construct]]内部方法
const Foo = () => {}
new Foo() // TypeError: Foo is not a constructor