0

I confident about that function declarations does not has lexical context and arrow function it does have, but I am confused if function expression does ?

According to what I read it doesn't but in the following example it works fine both ways( with function expression and arrow function ) so it seems to me it has lexical context. After my understanding arrow function it's just the short syntax of the function expression so it has the same capacities. Am I wrong?

See the uncommented code:

// Delete users for ADMIN with GET 
        document.addEventListener("click", function (e) {

            if (e.target.classList.contains("btnDeleteUser")) {
                /// get users based on id
                sUserId = e.target.getAttribute("data-userId");
                //console.log(sUserId);
                /*getAjax("api_delete_user.php?id=" + sUserId, function(ajUserDataFromServer) {
                deleteUser(e, ajUserDataFromServer);*/
                /*getAjax("api_delete_user.php?id=" + sUserId, (ajUserDataFromServer) => {
                    deleteUser(e, ajUserDataFromServer); 
                    })*/
                getAjax("api_delete_user.php?id=" + sUserId, deleteUser.bind(this, e));

            }
        });
CodeHip
  • 307
  • 4
  • 14
  • 3
    Possible duplicate of [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) – Zenoo Mar 05 '18 at 10:40
  • the point of my question is: does functions expressions assume the this of the lexically enclosing function context or not ? – CodeHip Mar 05 '18 at 10:46
  • the answer is no, function expressions follow `function` rules, i.e. `this` is dynamic. – georg Mar 05 '18 at 10:51
  • then why in the above example works fine ? `getAjax("api_delete_user.php?id=" + sUserId, function(ajUserDataFromServer) { deleteUser(e, ajUserDataFromServer);`or isn´t this a function expression ? – CodeHip Mar 05 '18 at 10:54
  • I am confused, after what I read it is a function expression used as a callback. https://dmitripavlutin.com/6-ways-to-declare-javascript-functions/#1functiondeclaration ( scroll to function expression ) – CodeHip Mar 05 '18 at 10:59
  • the link you provided is quite vague on the topic. It makes one assume (almost clearly says) that functions expressions are different from regular functions. Apart from the name, they are not different. On other hand, he should have explained more the difference with an arrow function, because using `this` is often important for callbacks – Kaddath Mar 05 '18 at 11:30

0 Answers0