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
test1is 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();
1 Answer 1
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.
test2.