javascript - 在 Javascript 中设置属性的默认值

标签 javascript oop default-value

如何为类的属性 p1p2p3 和 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/

相关文章:

C++ 继承和包含

c# - 在流畅的界面中实现条件

覆盖实例变量的默认值

javascript - RecordField 中的默认值在执行时引发 JavaScript 错误

javascript - 如果一个列表项没有内容或为空,则隐藏多个列表项

javascript - 加载资源失败:net::ERR_CONTENT_LENGTH_MISMATCH

java - 假设您只有类的字符串名称(以及方法名称/参数),如何从类调用静态方法 - 在 Java 中

c# - 该字段永远不会分配给并且始终具有其默认值 null

javascript - 在angularjs ng-include中延迟包含html文件

javascript - 可折叠列表 - 使用多行显示所有标题