Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding javascript variables

I am trying to better understand how variables are stored with JavaScript and jQuery.

Using the below code, a separate variable called default_value is created for each .default-value element. Is this correct? Can it only be accessed from within the anonymous function that created it? I've heard the term "namespace", and does it apply? Please provide any additional details so I can better understand what is going on.

Next, if I wanted to apply this to an element with a given ID instead of a group of a given class, then using each() appears unnecessary. How should it be modified?

$('.default-value').each(function() {
    var default_value = this.value;
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
        }
    });
    $(this).blur(function() {
        if($.trim(this.value) == '') {
            this.value = default_value;
        }
    });
});
like image 678
user1032531 Avatar asked Dec 20 '25 04:12

user1032531


1 Answers

Using the below code, a separate variable called default_value is created for each .default-value element. Is this correct?

Yes. The function is invoked for each, and the variable is scoped (via var) to the function.

Can it only be accessed from within the anonymous function that created it?

Yes (noting that the function creates more anonymous functions and they are within the function passed to each so they can also access it).

I've heard the term "namespace", and does it apply?

No

like image 189
Quentin Avatar answered Dec 22 '25 19:12

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!