Вопрос

Can we reuse var name without overwriting its details in JavaScript.Taking below example of augmented module pattern

  <script>

var Module = (function () {

  // Module object 
  var module = {},
    privateVariable = "Hello World";

  function privateMethod() {
    // ...
  }

  module.publicProperty = "Foobar";
  module.publicMethod = function () {
    //console.log( privateVariable );
    return privateVariable;
  };
  return module;

})();

 //Defining same name MODULE var again
var Module = (function (my) {
      var newvar = 999;
    my.anotherMethod = function () {
         return newvar;
    };

    return my;
}(Module));



alert(Module.publicMethod()); 
//How this upper MODULE property is accessible ? Should be  hide by 
//next same name MODULE var?**
alert(Module.anotherMethod());

</script>

Above code is running perfectly fine and adding one more anotherMethod under MODULE but how it is still accessing initial module property. Defining var with same name (MODULE) shoudn't overwrite (remove) the upper module.

Это было полезно?

Решение

Defining var with same name (MODULE) shoudn't overwrite (remove) the upper module.

Yes, it should.

The global scope (or the function if you are inside a function) is scanned for var statements. Since you have two identical ones, the second one is ignored. MODULE is created in the global scope.

Then you run a function and then assign its return value to the MODULE.

Then you run another function, passing the current value of MODULE as an argument to it, then you assign the return value to MODULE.

A reference to the object created at var my = {} still exists in the scope of the second function, but the only reference to it from the global scope has been overwritten.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top