Jshint.com | Assigning to 'this'

2019-07-14 03:46发布

In jshint.com whenever I do

var this_hold = this;

I get an error.

I get a violation of strict error.

The application is such that I need to work with either this ( passed in from an event handler) or I need to pull the element myself using document.getElementById()

It's just how this function works best...otherwise I have to write it twice once for each case.

I want the error gone..I don't want to turn it off. I want jshint.com 100% happy.

Here is the function in question with the violation commented

/**
 *vFlipBP - eliminate select_element in favor of 'this'
 */

function vFlipBP( element_or_string ) {
    var previous_page_element,
        previous_tag_element,
        current_page_element,
        select_element;
    console.log( 'element_or_string ' + element_or_string ); 
    if( typeof ( element_or_string ) === 'string' ) {
        select_element = document.getElementById( element_or_string );
    } else {
        select_element = this;  // violation of strict here
    }
    if( vFlipBP.previous_id === undefined ) {
        var probe_id = select_element.parentElement.firstChild.id;
        if ( ( probe_id === select_element.id ) && ( select_element.parentElement.firstChild.nextSibling ) ) {
            probe_id = select_element.parentElement.firstChild.nextSibling.id;
            vFlipBP.previous_id = probe_id;
        } else {
            vFlipBP.previous_id = select_element.id;
        }
    }
    current_page_element = document.getElementById( select_element.id + '_page' );
    current_page_element.style.display = '';
    select_element.style.background = "#eeeeee";
    if( vFlipBP.previous_id !== select_element.id ) {
        previous_page_element = document.getElementById( vFlipBP.previous_id + '_page' );
        previous_tag_element = document.getElementById( vFlipBP.previous_id );
        if( ( ( previous_page_element !== current_page_element ) ) && ( previous_page_element !== null ) ) {
            previous_page_element.style.display = 'none';
            previous_tag_element.style.background = "#ffffff";
        }
    }
    vFlipBP.previous_id = select_element.id;
}

2条回答
该账号已被封号
2楼-- · 2019-07-14 04:06

You can use an option validthis to turn off that warning. Unfortunately, you can't detect all strict mode violations just by doing static analysis so JSHint makes a guess—and sometimes it is wrong.

More about validthis and other options in our docs: http://www.jshint.com/docs/

查看更多
做个烂人
3楼-- · 2019-07-14 04:17

You can't assign to this; it's read-only.

However, assigning the value of this to another variable is not erroneous, and it does not violate "use stict" rules.

查看更多
登录 后发表回答