-1

I have defined a JavaScript object, inside which I have two functions test1 and test2.

When I call test1 inside test2 using this.test1(), it says

test1 is not a function

When I call test1 inside test2 using objectname.test1() it works fine.

Any reason why I can not call the other function using this?

 servicesFilteringObject = {
 init: function(){
 // Created Checkboxes dynamically and associated handleFilter on onclick of it
 },
 handlePrimeryContent: function(){
 // Some code
 },
 handleFilter : function(){
 servicesFilteringObject.handlePrimeryContent();// works
 this.handlePrimeryContent(); //does not work
 }
 }
 servicesFilteringObject.init();
dumbass
27.2k4 gold badges43 silver badges77 bronze badges
asked Jun 15, 2011 at 14:04
6
  • 11
    It is really so difficult to post code? Commented Jun 15, 2011 at 14:05
  • 4
    Show code. Including the code you use to call test2. Commented Jun 15, 2011 at 14:05
  • 7
    If you post your code, somebody will be able to tell you exactly what the problem is. Commented Jun 15, 2011 at 14:05
  • 6
    You are doing something wrong ;) That is all we can say for now. Commented Jun 15, 2011 at 14:05
  • The logic itself works so change your code according to this and it will work. Commented Jun 15, 2011 at 14:09

1 Answer 1

0

If "handleFilter" is invoked as

servicesPrimaryObject.handleFilter();

then this will reference that object ("servicesPrimaryObject"). However, if you pass a reference to that function to some other function, perhaps as an event handler, then when invoked from that other context there'll be no this. You can use "bind()" to fix that:

somethingElse(servicesPrimaryObject.handleFilter.bind(servicesPrimaryObject));

That will ensure that this inside the function will always be the right object when the function is invoked at some later point.

answered Jun 15, 2011 at 14:25
Sign up to request clarification or add additional context in comments.

1 Comment

OK - @Gopal note that ".bind()" is not present on old browsers, but the MDC documentation for bind includes a very solid piece of code you can use to add it where necessary.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.