-1

I have a function :

(function make_thread_active(thread_id=1)
{

$('#threadbox_' + current_thread_id).removeClass('active');
$('#threadbox_' + thread_id).addClass('active')
current_thread_id=thread_id;
    manager_name=threads[current_thread_id].manager_name;
company_name=threads[current_thread_id].company_name;
$('#manager_name').text(manager_name);
$('#company_name').text(company_name);
})()

As it is expected it runs automatically as the page is refreshed. But when I want to call it again via other methods like <p onclick=make_thread_active(1) > </p> it is giving me not defined.

In javascript console also when I try to run this function as make_thread_active(1) I am getting undefined error.

1 Answers1

3

But when I want to call it again via other methods like <p onclick=make_thread_active(1) > </p> it is giving me not defined.

Right. Named function expressions do not add a binding for the function to the scope in which they occur, only function declarations do that:

+function namedFunctionExpression(){};
function namedFunctionDeclaration(){}
console.log(`typeof namedFunctionExpression = ${typeof namedFunctionExpression}`);
console.log(`typeof namedFunctionDeclaration = ${typeof namedFunctionDeclaration}`);

So just use a declaration and then call it:

function make_thread_active(thread_id=1)
{
    $('#threadbox_' + current_thread_id).removeClass('active');
    $('#threadbox_' + thread_id).addClass('active')
    current_thread_id=thread_id;
        manager_name=threads[current_thread_id].manager_name;
    company_name=threads[current_thread_id].company_name;
    $('#manager_name').text(manager_name);
    $('#company_name').text(company_name);
}
make_thread_active();

I'd recommend using modules or similar to avoid having globals at all, though, and not using onxyz-attribute-style event handlers (using addEventListener and such instead). But that's a side point. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875