示例工程 05-objects-prototypes-class
05-objects-prototypes-class/03-class-vs-prototype/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— class 与「构造函数 + 原型」的等价与不等价
// 两者共享同一套原型模型;差异在严格模式、可枚举性、调用限制与 super。
export function PointFn(x, y) {
this.x = x;
this.y = y;
}
PointFn.prototype.norm = function () {
return Math.hypot(this.x, this.y);
};
export class PointClass {
constructor(x, y) {
this.x = x;
this.y = y;
}
norm() {
return Math.hypot(this.x, this.y);
}
static origin() {
return new PointClass(0, 0);
}
}
export function methodDescriptor() {
const fnDesc = Object.getOwnPropertyDescriptor(PointFn.prototype, 'norm');
const classDesc = Object.getOwnPropertyDescriptor(PointClass.prototype, 'norm');
return {
fnEnumerable: fnDesc.enumerable,
classEnumerable: classDesc.enumerable,
fnWritable: fnDesc.writable,
classWritable: classDesc.writable,
};
}
export function enumerableMethods() {
const f = new PointFn(3, 4);
const c = new PointClass(3, 4);
const fnKeys = [];
const classKeys = [];
for (const key in f) fnKeys.push(key);
for (const key in c) classKeys.push(key);
return { fnKeys, classKeys };
}
export function callWithoutNew() {
const results = {};
try {
PointFn(1, 2);
results.fn = '没有抛错';
} catch (e) {
results.fn = e.constructor.name;
}
try {
PointClass(1, 2);
results.class = '没有抛错';
} catch (e) {
results.class = e.constructor.name;
}
return results;
}
export function run(log = console.log) {
const f = new PointFn(3, 4);
const c = new PointClass(3, 4);
const desc = methodDescriptor();
const keys = enumerableMethods();
const calls = callWithoutNew();
const rows = [
['typeof 构造函数 / class', `${typeof PointFn} / ${typeof PointClass}`],
['实例方法结果一致', `${f.norm()} / ${c.norm()}`],
['方法在原型上(hasOwn 实例)', `${Object.hasOwn(f, 'norm')} / ${Object.hasOwn(c, 'norm')}`],
['typeof instance 的 proto', `${typeof Object.getPrototypeOf(f)} / ${typeof Object.getPrototypeOf(c)}`],
['原型方法 enumerable', `${desc.fnEnumerable} / ${desc.classEnumerable}`],
['for...in 实例', `${keys.fnKeys.join(',')} / ${keys.classKeys.join(',')}`],
['不带 new 调用', `${calls.fn} / ${calls.class}`],
['静态方法', `${PointClass.origin().norm()}`],
['constructor 指向', `${f.constructor.name} / ${c.constructor.name}`],
];
log('场景 => 结果');
for (const [label, value] of rows) log(`${label} => ${value}`);
log('-'.repeat(50));
log('要点:class 复用同一套原型链;区别是方法不可枚举、必须 new、自动严格模式、super 绑定。');
return rows;
}