JavaScript构造函数通过new调用时,this指向新实例并初始化专属属性;方法应定义在prototype上以共享,ES6 class是其语法糖,constructor中this作用相同。

在 JavaScript 中,构造函数模式通过 this 绑定新创建的实例对象,从而为每个实例初始化专属属性和方法。关键在于:构造函数被 new 调用时,this 自动指向一个全新的空对象,并且该函数默认返回这个对象(除非显式返回其他对象)。
构造函数内用 this 添加实例属性
在函数体中,直接给 this 赋值,就能把数据挂载到即将生成的实例上:
- 每个 new 出来的实例都有独立的一份属性,互不影响
- 属性名写在 this 后面,比如 this.name = name
- 参数通常用于接收初始化值,再赋给 this
例如:
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log('Hello, I\'m ' + this.name);
};
}
const alice = new Person('Alice', 28);
const bob = new Person('Bob', 32);
console.log(alice.name); // 'Alice'
console.log(bob.name); // 'Bob'
注意 this 的绑定时机和限制
this 在构造函数中生效的前提是必须用 new 调用。否则 this 会指向全局对象(非严格模式)或 undefined(严格模式),导致意外行为:
立即学习“Java免费学习笔记(深入)”;
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 直接调用 Person('Tom', 25) 不会初始化实例,还可能污染全局
- 建议函数名首字母大写(如 Person),作为构造函数的视觉提示
- 箭头函数不能用作构造函数,因为它没有自己的 this 和 prototype
配合 prototype 共享方法更高效
如果把方法定义在构造函数内部(如上面的 sayHello),每次 new 都会新建一份函数,浪费内存。更合理的方式是把方法挂到构造函数的 prototype 上:
- 所有实例共享 prototype 上的方法,节省内存
- this 在原型方法中依然指向调用它的实例
- 属性仍用 this 初始化,方法则委托给 prototype
改写示例:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log('Hello, I\'m ' + this.name);
};
const carol = new Person('Carol', 26);
carol.sayHello(); // 'Hello, I\'m Carol'
ES6 class 是构造函数的语法糖
class 写法本质仍是基于原型的构造函数,constructor 中的 this 作用完全一致:
- constructor 方法里用 this 初始化实例属性
- class 中定义的方法自动添加到原型上
- 同样必须用 new 调用,否则报错
例如:
class Animal {
constructor(species, sound) {
this.species = species;
this.sound = sound;
}
speak() {
console.log(this.sound);
}
}
const dog = new Animal('Dog', 'Woof');
dog.speak(); // 'Woof'

















