2

I'm having trouble figuring out why the following is not working:

My custom JS library

(function ($, undefined) {

var expenses = expenses || {};

expenses.report = function () {

    var deleteReport = function () {
        alert('test');
    };

    return {
        deleteReport: deleteReport
    };
};

window.expenses = expenses;

})(jQuery);

How I am calling it on the page:

$(function() { expenses.report.deleteReport() };

The error:

Uncaught TypeError: Object function () {



        var deleteReport = function () {

            alert('test');

        };



        return {

            deleteReport: deleteReport

        };

    } has no method 'deleteReport'

I'm still familiarizing myself with javascript and jquery so I'm sure there is something simple in the design that I am leaving out. I just can't figure out what it is.

1
  • Wow, this is Javascript run amok, way more obscure than needed. Commented Nov 4, 2011 at 21:02

3 Answers 3

3
expenses.report

is a function.

expenses.report()

is the return value of that function, which is the object you defined here:

{
    deleteReport: deleteReport
};

So if you want to call deleteReport, you need to go like this:

expenses.report().deleteReport()
Sign up to request clarification or add additional context in comments.

Comments

2

Currently, expenses.report is a function, which returns an object with a deleteReport method:

expenses.report().deleteReport();

If you instead wanted expenses.report.deleteReport(), you have a few options:

1) Change the function to auto-execute and return the object right away.

expenses.report = (function () {
    var deleteReport = function () {
        alert('test');
    };

    return {
        deleteReport: deleteReport
    };
})();

2) Set the object and function directly if you don't really need the closure or deleteReport as a separate variable.

expenses.report = {
    deleteReport: function () {
        alert('test');
    }
};

Comments

1

expenses.report is a function that returns an object when executed. Since it is never executed, the object containing deleteReport does not exist. I would make your expenses.report function self invoking, ie:

expenses.report = (function () {

    var deleteReport = function () {
        alert('test');
    };

    return {
        deleteReport: deleteReport
    };
})();

now you will be able to call expenses.report.deleteReport()

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.