最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JavaScript 中 class 语法中方法定义与原型链存储
时间:2026-07-07 11:25:59 编辑:袖梨 来源:一聚教程网
JavaScript类中非static方法自动挂载到prototype上,所有实例共享;constructor是类函数主体,非prototype属性;static方法挂载到类本身;getter/setter及私有字段访问器也添加至prototype。
JavaScript 中 class 语法里定义的方法,不会挂在实例上,而是自动添加到类的 prototype 对象中。这不是“约定”,而是语言规范强制的行为——它直接对应原型链的运作方式。
普通方法都进 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'为 true
constructor 是唯一写在函数体内的方法
constructor 不是“定义在 prototype 上的方法”,它是类本身的构造函数体,决定实例初始化时做什么。它本身是类函数的主体,不是 prototype 的属性。
- 省略时,JS 自动补一个空的
constructor() {} - 它执行时的
this指向新创建的空对象,并由new操作符自动链接__proto__到ClassName.prototype - 所以实例能用
greet()不是因为 constructor 里写了它,而是因为实例.__proto__ === Person.prototype
static 方法不进原型链
static 方法属于类本身,相当于直接挂在构造函数对象上,和 Person.doSomething = function(){} 效果一样。
立即学习“Java免费学习笔记(深入)”;
- 调用方式只能是
Person.staticMethod(),不能通过实例调用 - 它不在
Person.prototype上,也不参与原型链查找 - 它的
this指向类本身(Person),不是实例
getter/setter 和私有字段也走 prototype
类中声明的 get name()、set age(v) 或私有字段 #count 的访问器,最终也通过 Object.defineProperty 添加到 ClassName.prototype 上。
- 它们同样被所有实例共享,只是访问逻辑被封装
- 私有字段的存储位置虽在内部槽位([[PrivateNames]]),但其访问器方法仍位于 prototype
- 所以
instance.hasOwnProperty('name')返回 false,而'name' in instance为 true —— 正是因为从 prototype 链上继承而来
相关文章
- 如何登录QQ邮箱网页版 07-08
- 鄂汇办app如何重新注册二级建造师 07-08
- Soul私信功能异常如何解决 07-08
- 如何在火绒安全软件中进行右键管理菜单设置 07-08
- 智慧中小学课程教学如何删除 07-08
- 如何登录邮箱gmail 07-08