0

I have a want to create a object Metrics within which I need to initialize various other objects such as StatsD.

I know how to create Metrics object in javascript.

function Metrics(params) {
  // initialize params
}

Metrics.prototype.functionName = function() {

}

However I am confused is how to embed an object inside another object and access its methods ?

In java it would be easy:

class Metrics {
   StatsD statsD;
}

new Metrics().statsD.increment("foobar");

How would I do the same in javascript ?

0

2 Answers 2

2

You'd do it in the same way as in Java:

function Metrics(params) {
    this.statsd = new StatssD();
}

The only difference is that you don't have to declare the attribute with its type - just initialising the property in the constructor is enough.

Sign up to request clarification or add additional context in comments.

Comments

0

Just set the property (statsd in this case) to a new object (new StatsD()):

function Metrics(params) {
    //Initialize params
    this.statsd = new StatsD();
}

You could also attach the StatsD to the prototype:

Metrics.prototype.statsd = StatsD();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.