如何为类的属性 p1
、p2
、p3
和 p4` 设置默认值:
class O extends AnotherClass {
constructor(p1,p2,p3,p4) {
super(); \\ for the this-reference
if (p1) this.p1 = p1;
if (p2) this.p2 = p2;
if (p3) this.p3 = p3;
if (p4) this.p3 = p4;
}
一定要一一写吗
O.prototype.p1 = "default1"
O.prototype.p2 = "default2"
O.prototype.p3 = "default3"
O.prototype.p4 = "default4"
或者有更优雅的方式,比如
O.prototype = {p1: "default1", p2 : "default1", p3 : "default3", p4 : "default4"}
但是后者好像不行...
最佳答案
当你像这样在构造函数中声明参数时,你可以在 es6 中设置默认属性 constructor(p1 = 'Default Variable',p2 = 'Default Variable',p3 = 'Default Variable',p4 = 'Default Variable')
关于javascript - 在 Javascript 中设置属性的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42797619/