Trying to understand "this"


#1

Hi all,

I though I understood the “this” element until I read the following:

FormHandler.prototype.addSubmitHandler = function(fn){
    console.log('Setting submit handler for form');
    this.$formElement.on('submit', function(event){
        event.preventDefault();

        var data = {};
        $(**this**).serializeArray().forEach(function(item){
            data[item.name] = item.value;
            console.log(item.name + ' is ' + item.value);
        });
        console.log(data);
        fn(data);
        this.reset();
        this.elements[0].focus();
    });
};

Inside your submit handler callback , the this object is a reference to the form element.

My question is, why does “this” refer to the form element in this situation but not in other situations where you have to bind it?


#2

In JavaScript the only time you have any type of true binding is within the scope of a function. So “this” is pointing to the actual object either passed into the function or an object within the function’s scope.
I hope this helps.