search

Home  >  Q&A  >  body text

What is the difference between directly assigning a function to a variable and referencing a function?

What is the difference between directly assigning a function to a variable and referencing a function?

For example: Fragment 1 and Fragment 2

Fragment 1

function fn(){
  var box = document.getElementById("box");
  box.onclick = function(){
      console.log(111);
  };
  box = null;
}

Fragment 2

function fn(){
  var box = document.getElementById("box");
  box.onclick = click;
}

function click(){
  console.log(111);
}

The function in onclick in fragment 1 allows access to variables in fn, but the onclick function in fragment 2 does not allow access to variables in fn. I think so, because click in fragment 2 is defined outside fn. So the variables in fn cannot be accessed, so that means that the assignment to onclick in fragment 2 is actually a reference rather than a copy?

大家讲道理大家讲道理2774 days ago542

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:35:08

    No, no, you are not calling a method or passing parameters, so the core of these two examples is not a reference/copy issue

    This is a scope (prototype chain) problem

    Variables have different access rights in different scopes:
    Child scope can access parent scope
    Parent scope cannot access child scope
    Scopes at the same level cannot access each other

    reply
    0
  • PHPz

    PHPz2017-05-19 10:35:08

    I guess you may need to learn more about variable scope. The scope of js is already determined when it is defined.

    Clip 1

    function fn(){
      var box = document.getElementById("box");
      box.onclick = function(){
          console.log(111);
      };
      box = null;
    }
    The

    callback bound to onclickbox is inside the function of fn, so all local variables inside it can be accessed by the callback.

    Clip 2

    function fn(){
      var box = document.getElementById("box");
      box.onclick = click;
    }
    
    function click(){
      console.log(111);
    }

    click方法在fn函数外部,与之同级,由于定义时,clickis not yet inside fn, so its inner scope cannot be accessed.

    reply
    0
  • Cancelreply