简体   繁体   中英

Javascript how to avoid variable name conflicts in Functions?

I was working with dropzone and i noticed something strange:

This is my Drop:

<script type="text/javascript">

var CountFiles = 0;


$(document).ready(function () {

    Dropzone.autoDiscover = false;

    var new_file;

    const Drop1 = new Dropzone("div#myPrincipalDropzone", {
        url: "/Article/UploadFiles",

        paramName: "file",
        maxFiles: 1,
        maxFilesize: 1200,
        maxFileHeight: 840,
        maxFileWidth: 840,
        acceptedFiles: ".png,.jpg",
        addRemoveLinks: true,
        parallelUploads: 1,
        renameFile: function (file) {
            let newname = new Date().getTime() + '_';
            console.log("Nombre en RenameFile:" + newname);
            file.name = newname;
            console.log("Asigno al file el nombre:" + file.name);
            new_file = new File([file], newname + file.name);
            console.log(new_file.name);
            return new_file;
        },

        init: function (new_file) {

I noticed that my variable "new_file" at return statement has value of "123847123_Filename.ext" However when i try to call another method or function using that variable, i receive new_file as "Filename.ext" loosing my old value.

Searching on google i found that javascript have some conflicts with the name params between nested functions.

There is a way to fix this? I need to use my old value in multiple function/methods calls.

Edit 1: to correct confusion between context and scope

Edit 2: references to scope chain and removing "parameters" scope as there is no such thing

Well, the reason why it behaves like that is because of Closures

A function has access to 2 things:

  1. Local scope: variables defined inside of the function and parameters received. If defined they will be used in place of the variables available from the parent scope.
  2. Parent scope: variables defined in the scope in which the function was originally defined (often wrongly called "global" context). See Scope chains *

* The scope of a function is global to functions defined inside of it, therefore the parent's scope includes the scope of all upper parents until you reach the global scope.

Here's a snippet you can use to see a few of the many different cases that show how the context is everything when it comes to the "name" of a variable:


    const x = 'GLOBAL X VALUE';
    function A() {
      // A is referring to X within its own context
      console.log(`The value of x in A is => ${this.x}`);
      console.log(`The value of y in A is => ${this.y}`);
    }

    function B() {
      // B is referring to x within the context in which it was defined
      console.log(`The value of x in B is => ${x}`);
    }

    function C() {
      // C is referring to x within the context in which it was defined
      // That's why it also prints the value of the "global" context even if you
      // call it within a context that has a value with the same name
      console.log(`The value of x in C is => ${x}`);
    }

    function D(x) {
      console.log(`The value of x in D is => ${x}`);
      C();
    }

    function F() {
      // A is going to have access to the context of F, but it will not have access
      // to the global context
      this.y = "the other value";
      A.bind(this)();
      console.log(`The value of x in F is => ${x}`);
    }

    function G(x) {
      this.x = "HMMMM";
      console.log(`The value of local x in G is => ${this.x}`);
      console.log(`The value of param x in G is => ${x}`);
    }

    A(); // the value of x and y will be undefined
    B(); // the value of x will be the global context
    D("Parameter x value"); // the value of x will be the one passed as a parameter
    F();
    G("Parameter x value"); // the parameter and the local context are two different things

this * it's dangerous to go alone, take this documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM