1

What are the differences between the following two formats? Only format2 works.

Format1:

function test (e){
    var element = e.params.data.element;
    var $element = $(element);

    $element.detach();
    $(this).append($element);
    $(this).trigger("change");
}
$("#import-excel-id-select").on('select2:select', (e) => {
    test(e);
});

Format2:

$("#import-excel-id-select").on('select2:select', function (e){
    var element = e.params.data.element;
    var $element = $(element);

    $element.detach();
    $(this).append($element);
    $(this).trigger("change");
});
9

2 Answers 2

3

What are the differences between the following two formats? Only format2 works.

There are multiple, but the most important one, the reason why one works and the other doesn't is because the value of this is different in both cases.

In the second example, this refers to the DOM element the function is bound to, because the function is used as event handler.

In the first example you are calling test as test(e) from the event handler. When calling a function this way this either refers to the global object or undefined (when in strict mode). this does not refer to the DOM element, and hence all the jQuery(?) methods fail.

How a function is called matters in JavaScript. See MDN -this for more information.


There is also no reason to have a function that simply calls another function with the same arguments. The first example could be fixed by just passing test:

$("#import-excel-id-select").on('select2:select', test);
Sign up to request clarification or add additional context in comments.

Comments

2

Format 1 is another way of writing:

$("#import-excel-id-select").on('select2:select', function (e) { test(e); });

But inside function test(), $(this) might not be what you expected.

So, one way to fix it

$("#import-excel-id-select").on('select2:select', function (e) { test.call(this, e); // or test.bind(this)(e); });

And, () => {} only runs on very new browsers with ES6 support.

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.