Why is JSHINT complaining that this is a strict violation?

前端 未结 4 1792
悲哀的现实
悲哀的现实 2020-11-30 03:00

I think this may be a duplicate of Strict Violation using this keyword and revealing module pattern

I have this code:

f         


        
4条回答
  •  野性不改
    2020-11-30 03:15

    JSHint says "Possible strict violation" because you are using this inside something that, as far as it can tell, is not a method.

    In non-strict mode, calling gotoPage(5) would bind this to the global object (window in the browser). In strict mode, this would be undefined, and you would get in trouble.

    Presumably, you mean to call this function with a bound this context, e.g. gotoPage.bind(myObj)(5) or gotoPage.call(myObj, 5). If so, you can ignore JSHint, as you will not generate any errors. But, it is telling you that your code is unclear to anyone reading it, because using this inside of something that is not obviously a method is quite confusing. It would be better to simply pass the object as a parameter:

    function gotoPage(sorter, s) {
        if (s <= sorter.d && s > 0) {
            sorter.g = s;
    
            sorter.page((s - 1) * sorter.p.size);
        }
    }
    
    function pageChange(event, sorter) {
        var dd = event.currentTarget;
        gotoPage(sorter, dd[dd.selectedIndex].value);
    }
    

提交回复
热议问题