markzzz
markzzz

Reputation: 48065

Which of this version is more performant on jQuery?

First version :

$(".myClass").focus(function() {
    var MyRef=$(this);
    if (MyRef.val() == MyRef.attr("rel")) {
        MyRef.val("");
    }
});

$(".myClass").focusout(function() {
    var MyRef=$(this);
    if (MyRef.val() == "") {
        MyRef.val(MyRef.attr("rel"));
    }
});

Second version :

$(".myClass").focus(function() {
    if ($(this).val() == $(this).attr("rel")) {
        $(this).val("");
    }
});

$(".myClass").focusout(function() {
    if ($(this).val() == "") {
        $(this).val($(this).attr("rel"));
    }
});

So, without save this on a variable or use it? Or nothng change?

Upvotes: 0

Views: 53

Answers (4)

Alnitak
Alnitak

Reputation: 340055

The former is generally preferred - if you're going to use the same jQuery constructor over and over you should cache it.

That said, you actually don't need to use jQuery methods at all inside those functions - the following code would be more efficient than either:

$(".myClass").focus(function() {
    if (this.value === this.getAttribute('rel') {
        this.value = '';
    }
});

$(".myClass").focusout(function() {
    if (this.value === '') {
        this.value = this.getAttribute('rel');
    }
});

Upvotes: 2

WickyNilliams
WickyNilliams

Reputation: 5308

Caching the current Element in a wrapped jQuery set is recommended practice, as work is required to convert from standard DOM element to a jQuery wrapped set. I would therefore recommend the first approach.

A good approach for clarity is to follow a naming convention when you wrap a DOM element in a jQuery object. Personally i always call it $this - the dollar tells me its a jQuery object (another convention i use) and this tells me it's the current element

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

I think that the first one is better because it saves you from calling jQuery(this) (which is a call to a function) lot's of times

Upvotes: 1

James Allardice
James Allardice

Reputation: 166071

Saving a reference to a jQuery object containing this will be faster because you don't need to construct a new jQuery object every time you want to apply a jQuery method to this. In your first example there is one call to $. In the second example there are 3.

I'm not sure what you're doing here:

$(MyRef.val(MyRef.attr("rel"));

That should just be:

MyRef.val(MyRef.attr("rel"));

Upvotes: 2

Related Questions