0

I have this inside my html file:

<div class="messages">
      <input id="msg" type="text" name="fname">
      <input type="submit" onclick="general.add.call()" value="Send">
      <input type="submit" onclick="viewMsgs()" value="view messages">
    </div>

and in my js file

(function(){
  var general = new Channel();
  var rich = new Person('Rich');
  var rob = new Person('Rob');
  var message = new Message(rich, rob, "Hello!");
})()

and above that I have:

class Channel {
  constructor() {
    this.messages = [];
  }
  add(msg) {
    this.messages.push(msg)
  }

why is it saying that general is undefined?

2
  • 1
    It's because you nested the entire variable decleration inside function(){ for some reason Commented May 9, 2017 at 12:51
  • Variables live within an execution context. general exists within the execution context that it was declared, i.e. of the IIFE (function(){...})(), and can't be accessed from outside. Commented May 9, 2017 at 13:04

1 Answer 1

1

general is a local variable that exists only inside the IIFE that you wrapped around your code.

It isn't a global, so you can't access it as a global.

Bind your event handler using addEventListener (inside the IIFE) instead of using an onclick attribute.

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

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.