Why is this javascript incorrect?

My IDE, RubyMine, says this is "potentially incorrect":

function update_top_up_prices_via_localStorage(){
    var index = localStorage.getItem("volxs");
    $('.product-inner').each(function(){

        var product = this.getAttribute('data-product-miles');
        var cpm = ((localStorage.getItem("cpm_by_volxs_"+product)).split(","))[index];

        $(this).find('table tbody tr td').each(function(){
            var top_up_miles = Number(this.getAttribute('data-topup-miles'));
            var price = Number(top_up_miles * cpm * 1.06);
            price = price.toFixed(2);
            $(this).text('\u00A3'+price);
        })
    });
}

My IDE says on the var top_up_miles line, "potentially invalid use of this. This checks for javascript this to be the same in closure as in the outer context.

The js works fine in Chrome and IE9. It does not work in IE8.

Is this wrong? Is there a better way to write this?

Answers


RubyMine doesn't know that $().each executes the passed function with a specified this context. If you want to avoid that warning, use

$(/* ... */).each(function (i, elem) { 
    elem.getAttribute(/* ... */);
});

etc.

The reason your code doesn't work with IE8 probably has nothing to do with that. For greater compatability however, use jQuery-wrapped functions instead of native API functions: $(this).attr instead of this.getAttribute (thanks @freakish)


It draws your attention to warn you that you should be careful with using the this keyword in JavaScript, as this always refers to the function owner.

To learn more, see this article on quirksmode on the JavaScript this keyword.


Need Your Help

Python: Get name of shoutcast/internet radio station from url

python radio shoutcast

I've been trying to get the name/title of internet radio stations based on the url in python, but with no luck so far. It seems that internet radio stations use another protocol than HTTP, but please

How to apply ajax call to all model objects in DJANGO

jquery python ajax django django-views

I need to implement AJAX and its working fine. However, I am having problem in applying ajax to each instance of a model. It's just being applied on the top Object and applying ajax call on the sam...