JavaScript类中非static方法自动挂载到prototype上,所有实例共享;constructor是类函数主体,非prototype属性;static方法挂载到类本身;getter/setter及私有字段访问器也添加至prototype。
JavaScript 中 class 语法里定义的方法,不会挂在实例上,而是自动添加到类的 prototype 对象中。这不是“约定”,而是语言规范强制的行为——它直接对应原型链的运作方式。
你在 class 内写的非 static 方法(比如 greet()、toString()),编译后会被挂到 ClassName.prototype 上。这意味着所有实例共享该方法,不重复创建函数副本。
class Person { greet() { console.log(this.name); } }
Person.prototype.greet = function() { console.log(this.name); };
typeof Person.prototype.greet === 'function' 为 trueconstructor 不是“定义在 prototype 上的方法”,它是类本身的构造函数体,决定实例初始化时做什么。它本身是类函数的主体,不是 prototype 的属性。
constructor() {}
this 指向新创建的空对象,并由 new 操作符自动链接 __proto__ 到 ClassName.prototype
greet() 不是因为 constructor 里写了它,而是因为 实例.__proto__ === Person.prototype
static 方法属于类本身,相当于直接挂在构造函数对象上,和 Person.doSomething = function(){} 效果一样。
立即学习“Java免费学习笔记(深入)”;
Person.staticMethod(),不能通过实例调用Person.prototype 上,也不参与原型链查找this 指向类本身(Person),不是实例类中声明的 get name()、set age(v) 或私有字段 #count 的访问器,最终也通过 Object.defineProperty 添加到 ClassName.prototype 上。
instance.hasOwnProperty('name') 返回 false,而 'name' in instance 为 true —— 正是因为从 prototype 链上继承而来