0

In Swift I can instantiate one class within another as a property and call its methods using something like:

newClass.anotherClass.methodInTheOtherClass();

I am unable to do that in JavaScript. The following code produces an error in this line:

var cowCommunication = new CowCommunication();

What is the proper way to achieve this goal, and make the following script work?

<html >
  <script type = "text/javascript" >
  let CowCommunication = {
    sayMoo: function() {
      alert("hey");
    }
  };
let farmTools = {
  var cowCommunication = new CowCommunication();
};
farmTools.cowCommunication.sayMoo();

</script>
</html >

This is a real example of code I am actually trying to make work.

1
  • 1
    you can't use the var keyword inside of an object initializer in javascript, that's your main problem. look up the correct way to instantiate objects in javascript. Commented Feb 10, 2017 at 20:05

2 Answers 2

4
let farmTools = {
  cowCommunication : new CowCommunication(),
};

Not

let farmTools = {
  var cowCommunication = new CowCommunication();
};

Also :

class CowCommunication  {

    sayMoo() {
      alert("hey");
    }
}

Not :

let CowCommunication = {
    sayMoo: function() {
      alert("hey");
    }
  }
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you @Abdenour! I tried that and have received test.html:10 Uncaught TypeError: CowCommunication is not a constructor
is it ok now ? @MarkPurpelio
brilliant, Abdennour - yes! One final aspect: right now we have "farmTools.cowCommunication.sayMoo();" working. What if we wanted ONE MORE level, such as "farmTools.cowCommunication.newLevel.sayMoo();" ?
class NewLevel { sayMoo(){} } ; class CowCommunication { constructor() {this.newLevel= new NewLevel();}}
0

You can also use composition instead of Classes.

let cowCommunication = {
    sayMoo: function() {
      console.log('hey')
    }
};

const farmTools = function() {
  return Object.assign({}, cowCommunication)
}

let instance = farmTools()

instance.sayMoo()

2 Comments

thank you! but you end up with "instance.sayMoo()" i need "farmTools.cowCommunication.sayMoo();" i need to the dots, the second class, and the method from the second class, so to speak
The method is actually from the second object, it's just not notated that way; it's just inherited from the first object by way of prototypes, which is sort of the Class system of JS.

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.