不能在构造函数原型上用箭头函数定义方法,因为箭头函数没有自己的this,无法绑定实例对象,会导致this指向错误(如undefined或全局对象),必须使用普通函数或class语法。

别在构造函数原型上用箭头函数定义方法——它根本不会按你预期工作。
箭头函数无法绑定正确的 this
在原型上定义箭头函数时,this 不会指向实例,而是沿作用域链向上捕获外层的 this(通常是全局对象或 undefined):
function Person(name) { this.name = name; }Person.prototype.sayName = () => console.log(this.name); // this 不是实例,输出 undefinedconst p = new Person('Leo'); p.sayName(); // ❌
必须用普通函数语法
原型方法需要动态绑定调用时的实例上下文,只有普通函数能提供这种行为:
- 写成
Person.prototype.sayName = function() { console.log(this.name); };✅ - 或使用类语法:
class Person { constructor(name) { this.name = name; } sayName() { console.log(this.name); } }✅ - 避免任何形式的箭头函数赋值到
prototype上
常见误写场景及替代方式
以下写法都错误,需立即修正:
-
Person.prototype.init = () => { ... };→ 改为Person.prototype.init = function() { ... }; -
MyClass.prototype.handleClick = e => this.handle(e);→ 改为MyClass.prototype.handleClick = function(e) { this.handle(e); }; - React 类组件中,生命周期或自定义方法若写成箭头函数赋给
prototype,同样失效
本质原因就一条:箭头函数没有自己的 this,而原型方法的核心价值恰恰在于运行时绑定实例。绕过这点,就等于放弃了面向对象的基本契约。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











