3

Given the following how do i enable this to work correct?

return {

    methodA: function() {
        return methodB();
    },
    methodB: function() {
        alert("hi");
    }
}
5
  • 1
    return this.methodB(); Commented May 6, 2016 at 12:27
  • that did not work for me Commented May 6, 2016 at 12:27
  • is there any more code around this or is that all of it. Commented May 6, 2016 at 12:28
  • @MartinGlennon It cannot be all of it, you can't have a return outside of a function Commented May 6, 2016 at 12:39
  • true but it may also be part of the problem Commented May 6, 2016 at 12:41

2 Answers 2

5

You need to reference the context, via this.

var foo = {

    methodA: function() {
        return this.methodB(); //context
    },
    methodB: function() {
        alert("hi");
    }
}

foo.methodA(); //alerts "hi"
Sign up to request clarification or add additional context in comments.

1 Comment

As long as you call it like foo.methodA(), just a warning so the OP knows to avoid doing var func = foo.methodA and calls func(). See my answer for a safer alternative.
0

It seems you are returning from a module like function. The safe way is not to use this, it is to keep a reference to the object so that it won't matter how the function is called.

function getObj() {
  var obj = {
    methodA: function() {
      return obj.methodB();
    },
    methodB: function() {
        alert("hi");
    }
  };
  return obj;
}

var myObj = getObj();

// Works
myObj.methodA();
// Works but would not work if you were using `this` as suggested by Utkanos.
someDomElement.addEventListener('click', myObj.methodA);

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.