What is the difference between directly assigning a function to a variable and referencing a function?
大家讲道理
大家讲道理 2017-05-19 10:33:08
0
2
608

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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
我想大声告诉你

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

PHPzhong

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template