简体   繁体   English

JS吊装功能。 (为什么此代码段有效?)

[英]JS hoisting functions. ( Why does this code snippet work? )

The following code snippet shows a basic object that contains a variable str , a member variable hello , and a member function test . 以下代码段显示了一个基本对象,该对象包含变量str ,成员变量hello和成员函数test I thought I knew JS pretty well and expected this code to fail because the test function would be hoisted to the top and would be unable to access the str or vm variable. 我以为我非常了解JS,并希望此代码失败,因为test功能将被提升到顶部,并且将无法访问strvm变量。 I was then surprised to see that this actually works. 然后,我惊讶地发现这确实有效。 Why does this code function? 为什么此代码起作用? Does hoisting still occur? 仍会起吊吗?

function SomeObject( ) {
  var vm = this;
  vm.hello = "hello";
  vm.test = test;
  var str = "testig!";

  function test() { 
    console.log( vm.hello );
    console.log( str );
  } 
}


var s = new SomeObject();

s.test();

Output: 输出:

hello
testig!

Due to hoisting, you essentially end up with this: 由于吊装,您基本上会得到以下结果:

function SomeObject() {
  var vm;
  var str;
  var test;
  test = function test() {
    console.log(vm.hello);
    console.log(str); // Works because we haven't run the function yet
  }

  vm = this;
  vm.hello = 'hello';
  vm.test = test;
  str = 'testig'; // str now has a value, function hasn't been called yet
}

var s = new SomeObject();
s.test(); // Function is called after str has been given a value

All declarations are hoisted to the top of their enclosing scope container. 所有声明都被提升到其封闭范围容器的顶部。

A function declaration, such as: 函数声明,例如:

 function foo(){ }

Will be hoisted to the top of its enclosing scope, so it may be called by code that is written BEFORE the function is. 将被提升到其封闭范围的顶部,因此可以通过在该函数之前编写的代码来调用它。

Variable declarations are hoisted as well. 变量声明也被吊起。 So, code such as: 因此,代码如下:

 var x = 10;

Will experience hoisting as well. 也会经历吊装。 BUT, only declarations are hoisted, so in the previous example, only 但是,只有声明会被悬挂,因此在前面的示例中,只有

 var x

is hoisted. 悬挂。 The x = 10 assignment won't happen until the actual code location is reached. 在达到实际代码位置之前,不会发生x = 10分配。

Similarly, function expressions work the same way. 同样,函数表达式的工作方式相同。 With this code: 使用此代码:

 var f = function() {};

Only the var f is hoisted, not the assignment. 仅挂起var f ,而不挂起分配。 If you were to try to call f before the actual code location were reached, you would receive an error indicating that f is not a function. 如果要在到达实际代码位置之前尝试调用f,则会收到一条错误消息,指出f不是函数。

Your code works simply because when you call: 您的代码之所以有效,仅是因为您在调用时:

 var s = new SomeObject();

The function test is not executed, but all the variable assignments are. 功能测试未执行,但所有变量分配均已执行。 So, when the time comes for this: 因此,当需要这样做的时候:

 s.test();

All the variables and the function are ready to go. 所有变量和函数均已准备就绪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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