2

I have a function like this:-

function test() {
    // code here
}

I want to assign the function test() to a global variable so that I should be able to call the function from elsewhere in the script using window.newName(). How can I assign this?

I tried window.newName = test();, but it didn't work. Please advice.

1
  • 3
    Tried window.newName = test;? Commented Dec 18, 2012 at 14:27

4 Answers 4

3

You are close:

window.newName = test;

If you include the braces, as you did, it will assign the result of executing the function, rather than the function itself.

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

1 Comment

then I can call the function like window.newName() ?
2

When using window.newName = test() you are actually activating the function and that way, the variable will get the value returned from the function (if any) and not a reference to the function.

You should do it like this:

window.newName = test;

Comments

1

Don't call the variable, just assign it:

window.newName = test;

If you don't need to call it using its original name, you can use a function expression as well:

window.newName = function() {
    // code here
};

Comments

1

When you do window.newName = test(), it really means "call test, and assign its return value to window.newName.

What you want is window.newName = test;

Comments

Your Answer

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.