2

I created MyObject in javascript and I need to return its method like this

var m = new MyObject();
document.onclick = m.myMethod;

But the problem is, all the m instance variables appear to be undefined, I can't access them (even though they are defined on m) and operations on them result in NaN. How do I do this properly, so instance variables stay set when method is executed?

3
  • Can you specify the MyObject code? Commented Feb 5, 2014 at 13:30
  • Is it as simple as you forgetting to use the new keyword? var m = new MyObject();? Commented Feb 5, 2014 at 13:31
  • EDIT: added "new" which was not in post, but was in code, so it is not the problem. Commented Feb 5, 2014 at 13:38

1 Answer 1

5

It is because the this scope is the html element, not the instance.

Either a closure

document.onclick = function(evt) { m.myMethod(evt); }

or bind

document.onclick = m.myMethod.bind(m);

is needed to maintain the scope you are after.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.