David Gard
David Gard

Reputation: 12077

Why does JS report 'this.function' as not being a function?

I wonder if somebody could please help me understand something that seems odd with JS?

The below code works. The function inlineEditEvent.init() is called, and then t.copy() is called correctly (where var t = this;).

However, if I was to replace that with this.copy(), I get the error this.copy is not a function.

What's the difference here? Why does the below work, but not the way as described in the last paragraph? Thanks.

jQuery(function($){

    $(document).ready(function(){inlineEditEvent.init();});

    inlineEditEvent = {

        init : function(){

            var t = this;

            /** Copy the row on click */
            $('#the-list').on('click', '.row-actions a.single-copy', function(){
                return t.copy();
            });

        }, // init

        copy : function(){

            // Do stuff here

        }

    } // inlineEditEvent

});

Upvotes: 1

Views: 93

Answers (4)

Jnatalzia
Jnatalzia

Reputation: 1687

When you say var t= this; it refers to what this meant in that context. Later on when you are trying to refer to this, it is referring to a.single-copy instead since that is the new context it is in.

Upvotes: 1

Prisoner
Prisoner

Reputation: 27628

this refers to this within the functions scope. That's why you need to set a self variable, so it's accessible within the scope of the function. Considering you're using jQuery, you could use $.proxy:

$.proxy(function(){
    return this.copy();
},this)

Upvotes: 1

Quentin
Quentin

Reputation: 944443

t.copy(); appears in a different function to var t = this;. The value of this changes inside each function.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104795

You're setting t as a context variable of this (of your init function). Once inside your click handler, this is now referring to the click handler, no longer the init function. Therefore, this.copy() is not a function.

Upvotes: 2

Related Questions