SunnyShah
SunnyShah

Reputation: 30467

How to have nested objects in JS?

I am a c++ programmer, Here is a C++ code, how to have similar JS code,

class A {
 public:
  void sayHello();
};

class B  {
 public:
  A a;
};

main()
{
 B b;
 b.a.sayHello(); 
}

Upvotes: 0

Views: 76

Answers (2)

Lloyd
Lloyd

Reputation: 29668

The most basic and simplest example:

function A() {
  return {
    sayHello: function() {

    }
  }
}

function B() {
  return {
    a: new A()
  }
}

var b = new B();

b.a.sayHello();

Upvotes: 1

Victor Nicollet
Victor Nicollet

Reputation: 24577

// Define class A
function A() {}
A.prototype.sayHello = function() { alert('hello!'); };

// Define class B
function B() { this.a = new A(); }

// Use them
var b = new B();
b.a.sayHello();

Upvotes: 6

Related Questions