gpt4 book ai didi

javascript - es6类可以继承Math对象吗?

转载 作者:行者123 更新时间:2023-11-29 16:31:31 26 4
gpt4 key购买 nike

我可以在我的类中扩展 Math 对象吗?我希望 Math 静态字段在我的类中是静态的。

class MyClass extends Math {
constructor() {
super();
}
}

console.log(MyClass.PI);

最佳答案

我想你可以使用函数而不是并使用setPrototypeOf:

function MyClass() {
}
Object.setPrototypeOf(MyClass, Math);
MyClass.prototype = Object.create(Math);

console.log(MyClass.PI);

但是Math无法实例化。像类一样使用它没有多大意义。仅使用继承自 Math 的普通对象可能更有意义:

const MyObj = Object.create(Math);
MyObj.someOperation = () => {
console.log('some operation');
};

console.log(MyObj.PI);
MyObj.someOperation();

关于javascript - es6类可以继承Math对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com