0

I am not sure if I am doing this right.

var pagefunction = function() {

    anotherfunction(){
        alert("it worked");
    }
}

pagefunction.anotherfunction();

Basically I am trying to call a function inside another function, would anyone be able to advise what I am doing wrong?

5 Answers 5

3

You may try this:

var pagefunction = function() {
    return function(){
        alert("it worked");
    };
};

To invoke:

pagefunction()();

OR:

var fn = pagefunction();
fn();
Sign up to request clarification or add additional context in comments.

1 Comment

+1 because this is super neat, but please realize that the techniques used here (closures & functional programming) are a bit hard to wrap your head around at first, so don't get too confused. Just look up those as search terms and you'll get it.
2
var pagefunction = {
    anotherfunction:function(){
        alert("it worked");
    }
}
pagefunction.anotherfunction();

For more details visit http://www.sitepoint.com/5-ways-declare-functions-jquery/

1 Comment

+1 (+ more if I could) I never thought about that method! Awesome job!
2

You have a basic syntax error.

You're calling anotherfunction but then adding a body like you're trying to declare it or something. You can't do that. This is what it should look like:

var anotherfunction = function() {
    alert("It Worked!");
}

var pagefunction = function() {
    anotherfunction();
 }

pagefunction();

Comments

1

To call a function, you just write the function name followed by parentheses, with parameters inside the parentheses. You don't put { ... } after it, that's for defining a function.

var pagefunction = function() {
    anotherfunction(); // Call the other function
    alert("it worked!"); // Alert after the other functioin returns
}

You call this as just:

pagefunction();

In order to use:

pagefunction.anotherfunction();

pagefunction would have to be an object, not a function. That object would have a property named anotherfunction that contains a function.

Or if you wanted to write:

pagefunction().anotherfunction();

pagefunction would have to be a function that returns an object, and that object would have to have a property named anotherfunction that contains a function.

Comments

0

I would use something like below.

var pagefunction = (function () {
    return new function () {
        var that = this;
        that.another = function () {
            alert("it worked");
        };
    };
})();

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.