为 Javascript 中的属性设置默认值
Setting default values for properties in Javascript
如何为 class:
的属性 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')
除了 @Fried_Chicken 已经回答的普通 ES2015+ 默认参数值之外,还有另一种方法。
为什么不接受参数作为 object 然后,你使用 ES2015+ 解构功能?这是一个很好的选择,因为您可以按任何顺序提供所有参数,甚至可以只提供其中一个或部分参数。
此外,您不需要为某些给定参数提供 null
/undefined
:
doStuff(1, null, null, 2);
查看以下可运行代码片段并使用它。可以在您的场景中应用相同的解决方案,因为可以在 class 构造函数上使用解构。
function doStuff({ arg0 = null, arg1 = null } = {}) {
if (arg0 !== null) {
console.log(arg0);
} else {
console.log("not provided");
}
}
doStuff();
doStuff({ arg0: "hello world" });
constructor(p1, p2, p3, p4) {
super();
if (p1) this.p1 = p1 === undefined ? "p1Default" : p1;
if (p2) this.p2 = p2 === undefined ? "p2Default" : p2;
if (p3) this.p3 = p3 === undefined ? "p3Default" : p3;
if (p4) this.p3 = p4 === undefined ? "p4Default" : p4;
}
如何为 class:
的属性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')
除了 @Fried_Chicken 已经回答的普通 ES2015+ 默认参数值之外,还有另一种方法。
为什么不接受参数作为 object 然后,你使用 ES2015+ 解构功能?这是一个很好的选择,因为您可以按任何顺序提供所有参数,甚至可以只提供其中一个或部分参数。
此外,您不需要为某些给定参数提供 null
/undefined
:
doStuff(1, null, null, 2);
查看以下可运行代码片段并使用它。可以在您的场景中应用相同的解决方案,因为可以在 class 构造函数上使用解构。
function doStuff({ arg0 = null, arg1 = null } = {}) {
if (arg0 !== null) {
console.log(arg0);
} else {
console.log("not provided");
}
}
doStuff();
doStuff({ arg0: "hello world" });
constructor(p1, p2, p3, p4) {
super();
if (p1) this.p1 = p1 === undefined ? "p1Default" : p1;
if (p2) this.p2 = p2 === undefined ? "p2Default" : p2;
if (p3) this.p3 = p3 === undefined ? "p3Default" : p3;
if (p4) this.p3 = p4 === undefined ? "p4Default" : p4;
}