实现说明
活动部件是类 Point、Point3D。
plain 定义在模块顶层,中间不经过函数作用域。
使用要点
- 演示输出是带标签的(
prototype is Point3D:、describe:、z is undefined:),每个操作都会留下自己的一行标注。
常见问题
不安装任何包也能运行吗?
可以,开箱即跑——没有引用任何内建 API 之外的东西。 状态都挂在模块顶层:plain。
核心语句
return '(' + this.x + ', ' + this.y + ')';
return super.describe() + ' z=' + this.z;
代码示例
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
describe() {
return '(' + this.x + ', ' + this.y + ')';
}
}
class Point3D extends Point {
constructor(x, y, z) {
super(x, y);
this.z = z;
}
describe() {
return super.describe() + ' z=' + this.z;
}
}
// Reflect.construct(target, args, newTarget):借用构造器但换原型
const p = Reflect.construct(Point, [1, 2], Point3D);
console.log('prototype is Point3D:', Object.getPrototypeOf(p) === Point3D.prototype);
console.log('describe:', p.describe());
console.log('z is undefined:', p.z === undefined);
// 对照:普通 new 只产出 Point 实例
const plain = new Point(3, 4);
console.log('plain:', plain.describe(), '| instance of Point3D:', plain instanceof Point3D);