2

I'm using functions as representations of classes.

function ClassOne()
{
  this.doFunc = function() {
    console.log("doFunc output");
  }
}

function ClassTwo()
{
  this.one = ClassOne();
  console.log(this.one); // == undefined ???

  this.init = function() {
    this.one.doFunc();
  }

  this,init();
}

ClassTwo();

But I'm struggling to use one function inside another.

For example, the above code returns "Cannot read property 'doFunc' of undefined"

Why is this.one == undefined?

2
  • Why is this.one == undefined?: Because you are executing the function and the function has no return statement. Therefore, it returns undefined and assigns that to your this.one property. Commented Dec 6, 2018 at 4:47
  • 1
    You need to use new ClassOne() is you want it to make an instance for you. Commented Dec 6, 2018 at 4:48

1 Answer 1

2

If you assign to a property of this inside a function, generally that indicates that the function is intended to be called as a constructor with new, eg:

this.one = new ClassOne();

Otherwise, if the function doesn't return anything... then, well, nothing gets returned (=> undefined)

function ClassOne()
{
  this.doFunc = function() {
    console.log("doFunc output");
  }
}

function ClassTwo()
{
  this.one = new ClassOne();
  console.log(this.one);

  this.init = function() {
    this.one.doFunc();
  }

  this.init();
}

ClassTwo();

Or, you can have ClassOne explicitly return an object with a doFunc property, allowing it to be called without new:

function ClassOne()
{
  return {
    doFunc() {
      console.log("doFunc output");
    }
  }
}

function ClassOne() {
  return {
    doFunc() {
      console.log("doFunc output");
    }
  }
}

function ClassTwo() {
  this.one = ClassOne();
  console.log(this.one);

  this.init = function() {
    this.one.doFunc();
  }

  this.init();
}

ClassTwo();

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.