声明对象时,如何在同一个对象的另一个属性内使用以前的对象属性的值

时间:2019-04-22 18:13:59

标签: javascript class object ecmascript-6

我有一个返回其属性的对象的类。我想访问构造函数中以前的prop的值。

我有下一个工作代码:

class KafkaConsumer {
    constructor (metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName) {
        return { 
            consumer: this.create(metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName),
            connect: (consumer) => { this.connect(consumer) }
        };
    }


    create (metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName) {
        var consumer = new Kafka.KafkaConsumer({
            'metadata.broker.list': metaDataBrokerList,
            'group.id': groupID,
            'enable.auto.commit': autoCommit, // don't commit my offset
            'auto.offset.reset': AutoOffsetReset, // consume from the start
        });

        .
        .
        .

        return ( consumer );
    }

    // Conect the consumer
    connect (consumer) {
        consumer.connect();
    }
}

调用是(如您所见,我需要将创建的变量传递给函数“ connect”。我想避免这种情况):

let kafkaConsumer = new KafkaConsumer(...props);
// Connect the consumer
kafkaConsumer.connect(kafkaConsumer.consumer);

我想要类似的东西:

class KafkaConsumer {
    constructor (metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName) {
        return { 
            consumer: this.create(metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName),
            connect: this.connect(consumer) 
            // Where 'this.connect' is my function and 'consumer' is the previous prop
        };
    }

    .
    .
    .

}

因此呼叫应为:

// Connect the consumer
kafkaConsumer.connect();

2 个答案:

答案 0 :(得分:0)

目前还不清楚您要实现什么目标。

  • 为什么要在构造函数中返回某些内容?
  • 为什么需要一个create方法,该方法只返回一个具有构造函数中参数的对象?
  • connect方法应该做什么?

如果您尝试创建使用者对象并将其返回,则此解决方案可能对您有用:

class KafkaConsumer {
    constructor (metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName) {
        this.consumer = {
            'metadata.broker.list': metaDataBrokerList,
            'group.id': groupID,
            'enable.auto.commit': autoCommit, // don't commit my offset
            'auto.offset.reset': AutoOffsetReset, // consume from the start
        }
    }

    get() {
        return this.consumer;
    }
}

并像这样使用它:

let consumer = new KafkaConsumer(props);
consumer.get(); // Returns your created consumer

答案 1 :(得分:0)

我实现了我的目标。我已经完成了该类的每个属性都与它的私有函数相关联的操作,因此,每个类属性都是一个调用另一个私有函数的函数:

class KafkaConsumer {
    constructor (metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName) {
        this.consumer = this.p_create(metaDataBrokerList, groupID, autoCommit, AutoOffsetReset, topicName);
        this.connect = () => { this.p_connect() };
    }

    // Conect the consumer
    p_connect () {
        this.consumer.connect();
    }