Don't use <button onclick="...">
. If you're using jQuery, get the element using selectors and set up an event listener.
$('button').click(function(){
...
});
The code you've posted it a bit barmy, and not readable. It could use refactoring.
If you insist on leaving it how it is, you can do this...:
$(document).ready(function () {
function Test() {
var that = this;
that.testFunc = function() {
//alert('i will also fire when this.testFunc() is called.');
}
// alert('i will fire');
this.testFunc();
}
$('button').click(function(){
Test();
});
});
Here's a fiddle of that working.
The coding-style is a poor attempt at OO-Javascript. W3Schools (I know...) could be a good place to start understanding what it's all about. Alternatively, this post on Stack is all about the this
keyword, and has some links to great resources.
TLDR; Code looks really clever, but is just confusing and rubbish.
Update
Ok, so here's what happens.
$(document).ready(function () { // when the page is loaded, run this function
function Test() { // create a named function called Test.
// Note that this function is only visible (so can only be called) within the anonymous function being run after $(document).ready.
var that = this; // set a variable ('that') to 'this' - a special keyword. At this point, 'this' will refer to the Global scope.
that.testFunc = function() { // create a function called testFunc on the object which is now 'that' - i.e. Global scope, the Window object.
// basically, create window.testFunc.
//alert('i will also fire when this.testFunc() is called.');
}
// alert('i will fire');
this.testFunc(); // call window.testFunc();
}
$('button').click(function(){
Test(); // run the Test function explained above
});
});
So, if you don't refactor, you need to do something like:
$(document).ready(function(){
function Test(){
var that = this;
that.testFunc = function(){
...
};
}
$('button').click(function(){
testFunc();
});
Test();
});
Basically, you need to run Test() to create testFunc
as part of the Global Scope. The code is difficult to follow, and can easily be misinterpreted - so I implore you to refactor and get it done properly.
Here's (another) fiddle of the button just calling testFunc
.