Understanding javascript variables

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

Using the code below, a separate variable named default_value is created for each .default-value element. It's right? Is it possible to access only from the anonymous function that created it? I heard the term "namespace" and does it apply? Please provide additional details so that I can better understand what is happening.

Further, if I wanted to apply this to an element with a given identifier instead of a group of this class, then using each () seems unnecessary. How to change it?

$('.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;
        }
    });
});
+3
source share
4 answers

What you are talking about is scoping .

, var ( ), ( ).

var, global.

( ) DOM, :

$('#theid').focus(function() { });

, , JQuery hover, .focus(), .blur():

$('#theid').hover(function() {
  // focus in your code
}, function() {
  // blur in your code
});
+3

, .default-value default_value. ?

. , ( var).

, ?

(, , , each, ).

" " ?

+7

var javascript, , , var defaulf_value .

var .

JavaScript JSON.

javascript, , :

mynamespace = {};

, , :

mynamespace.variableA = "Hello there";

, . , :

variableA = "First hello there";
mynamespace.variableA = "Second hello there";

console.log(variableA);
console.log(mynamespace.variableA);

:

"First hello there"
"Second hello there";

, , , =)

+2

default_value .default-value. ?

, . default_value jQuery node, . , , , .

, ?

, , .

" " ?

The term namespace indicates a container of functions and variables. If you are creating a new JS library, it is very important to avoid conflict with another library. Therefore, instead of creating a global "load" function, you create a namespace that will contain this function:

var myLibraryUniqueName = {};
myLibraryUniqueName.load = function() {};

Of course, if the library is complex, you can create internal namespaces:

myLibraryUniqueName.loginModule = {};
myLibraryUniqueName.animationModule = {};
...

Then you asked:

if I wanted to apply this to an element with a given ID instead of a group of this class, then using each () seems unnecessary. Like if it will be changed

function defaultValue(node) {
  var default_value = node.value;
  node.focus(function() {
      if(node.value == default_value) {
          node.value = '';
      }
  });
  node.blur(function() {
      if($.trim(node.value) == '') {
          node.value = default_value;
      }
  }
}
defaultValue($('#id'));
+1
source

All Articles