实例方法是挂载在类原型上的函数,通过类的实例调用,用于操作该实例的数据;定义时在class内constructor外声明普通函数,自动添加到prototype,this指向当前实例,需new后调用。

实例方法是挂载在类原型上的函数,通过类的实例调用,用于操作该实例的数据。
定义实例方法
直接在 class 大括号内、constructor 外声明普通函数即可。这些方法自动添加到类的 prototype 上,所有实例共享同一份方法代码:
- 不加 static 关键字
- 方法内部可用 this 访问当前实例的属性
- 无需显式绑定,new 实例后可直接调用
示例:
constructor(brand, year) {
this.brand = brand;
this.year = year;
}
// 实例方法
getInfo() {
return `${this.brand} (${this.year})`;
}
start() {
console.log(`${this.brand} engine started.`);
}
}
调用实例方法
必须先用 new 创建实例,再通过点语法(.)调用:
立即学习“Java免费学习笔记(深入)”;
- 调用时 this 自动指向该实例
- 不能通过类名直接调用(如
Car.getInfo()会报错) - 多个实例调用互不影响,各自维护自己的 this 状态
示例:
const myCar = new Car('Toyota', 2022);console.log(myCar.getInfo()); // "Toyota (2022)"
myCar.start(); // "Toyota engine started."
注意几个关键点
- 实例方法不是闭包,不捕获定义时的外部变量,只依赖 this 和参数
- 如果在回调中使用(如 setTimeout),需注意 this 绑定问题,可用箭头函数或
.bind(this) - 方法名不能叫
constructor,那是保留字,用于构造函数


















