2

Quick question: How do I get a pointer to a pre-declared function in javascript.

Say in my .js file I have

function a() {
    var bref = `a pointer/ref to b() here`
}

function b(param) {
    ...
}

I want bref to be simply a pointer to the function b and not just the result of a call to b()

Edit: Forgot to mention: function b takes in one parameter i.e b(param)

Have tried bref = b

2 Answers 2

6

Just use the function name for assignment.

To call the function you can use

call

or

apply

methods.

e.g:

function a() {
    var bref = b;
    .
    .
    b.call(null, "Something")
}

function b(src) {
    ...
  alert(src);
}

Working example @: http://jsfiddle.net/UasYH/1/

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

1 Comment

Sorry forgot to mention, b takes a parameter. I tried doing: bref = b But it still has problems.
2

You can simply:

function a() {
    var bref = b;
    ...
    x = bref("cake");
}

function b() {
    ...
}

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.