Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Scope: this.remove is not a function

this.remove() is not a function. How come?

var vehicle = function () {
    return {
        init: function () {
            jQuery('.vehicle-year-profile .options .delete').bind('click', function (e) {
                e.preventDefault();
                this.remove();
            });
        },
        remove: function () {
            alert('test');
        }
    }
}();

jQuery().ready(vehicle.init);

Sorry for the confusion. I'm trying to call my own "remove" function. This is simply a class to manage vehicles on my page. This is the beginning of it and it will have a lot more functions than just init/remove.

like image 506
Webnet Avatar asked Sep 20 '10 18:09

Webnet


People also ask

Is not a function error JS?

This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute a function that is not initialized or is not initialized correctly. This means that the expression did not return a function object.

Can I put a function inside a function JavaScript?

Nested functions A function is called “nested” when it is created inside another function. It is easily possible to do this with JavaScript. Here the nested function getFullName() is made for convenience. It can access the outer variables and so can return the full name.

Can I call a function inside another function JavaScript?

Approach: Write one function inside another function. Make a call to the inner function in the return statement of the outer function. Call it fun(a)(b) where a is parameter to outer and b is to the inner function.


1 Answers

this is a DOM element. To use jQuery's .remove() method, you need to wrap it in a jQuery object.

$(this).remove();

EDIT: If you were hoping to call the remove() function in the vehicle object, then call:

vehicle.remove();

Also, if you were hoping to shorten your .ready() call, you can do this:

jQuery(vehicle.init);

From the jQuery 1.4 release notes:

The jQuery().ready() technique still works in 1.4 but it has been deprecated. Please use either jQuery(document).ready() or jQuery(function(){}).

like image 153
user113716 Avatar answered Oct 05 '22 23:10

user113716