Home  >  Article  >  Web Front-end  >  Various common function definition methods in JavaScript_javascript tips

Various common function definition methods in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:36:231228browse

This article details various common function definition methods in JavaScript and shares them with you for your reference. The specific analysis is as follows:

First, let’s take a look at the four most common function definitions in JavaScript:

The function defined using the Function constructor, the code is as follows:

var multiply = new Function('x', 'y', 'return x * y;');

Function declaration, this method is also the most common one:

function multiply(x, y) {
  return x * y;
}

Function expression, declared as an anonymous function and then assigned to a variable, a very common way:

var multiply = function(x, y) {
  return x * y;
}

Function expression, but the function is declared as a named function and then assigned to a variable. It looks exactly like the previous method:

var multiply = function multi(x, y) {
  return x * y;
}

First, let’s compare the direct relationship between the function name and the function variable to which the function is assigned. It’s really confusing... To be more intuitive, let’s talk about it from Example 4 just now. It is the relationship between the function variable multiply and the function name multi. :

The function name cannot be modified. On the contrary, the function variable can be reassigned. It should be easy to understand that function variables can be reassigned. The multiply variable we just defined in our fourth example is not pleasing to the eye, so it can be reassigned as:

multiply = function(x, y) {
  return x + y;
}

Immediately transformed from multiplication to addition. But it is impossible to change the function variable multi. The function definition is already there. As long as the reference to it is still retained, it will not change. Maybe it is not easy to understand here. Think about it like this first and read on. You should be able to understand it gradually.

The function name cannot be used outside the function. It is only visible inside the function body. A very simple example:

var foo = function bar() {
  alert('hello');
}
foo(); // 提示“hello”字符串
bar(); // 执行报错,bar未定义

Obviously, bar here is indeed a function name, but it cannot be called externally. At this time, some children will definitely ask why this example still looks so good. It is the same as Example 4. Why not use the method of Example 2? Good question, let me break it down slowly.

Continuing with Example 4, we can see that the function name (multi) and the function variable (multiply) are not the same. In fact, they have no relationship at all, so there is no need to keep them consistent. Speaking of which, I think the above four examples can be reduced to three. Examples 2 and 4 should be essentially the same. What, don’t believe it? Hee hee, I have to continue to tell the truth~keep reading~~

We found that compared with Example 4, Example 2 only lacks the function variable of var, and compared with Example 4, Example 3 only lacks the function name. From the perspective of the phenomenon, Example 2 and Example 4 The essence is the same, the ironclad proof is as follows:

function foo() {}
alert(foo); // 提示包含“foo”的函数名
var bar = foo;
alert(bar); // 提示依然只包含“foo”的函数名,和bar半毛钱关系都没有

Is it indeed irrefutable evidence? Can the code similar to Example 2 above be combined and written in the same way as Example 4? Correct, this is what I just said. The essence of the two should be the same. It’s just that when defining the function in use case 2, the JS engine did some things for us, such as declaring a function named multiply, and also quietly defined a function called multiply. Call the variable multiply, and then assign it to this variable. The two names are exactly the same. When we think that when we use the function name multiply, we are actually using the function variable multiply. I am confused~ To be honest, I am also confused~ ~In short, when we call, we actually use function variables to call, and the function name cannot be used to call the function externally, so I have the above inference.

But there is a small difference to be mentioned here. The difference between functions defined in function declaration mode and constructor declaration or function expression declaration is that functions in function declaration mode can be called before the function is defined. ...I won’t talk anymore, let’s look at the code:

foo(); // 提示Foo
function foo() {
  alert('Foo');
}
bar(); // 哥们,和上面确实不一样,就不要逞能,这不报错了?提示bar未定义
var bar = function() {
  alert('Bar');
}

Let’s talk about the function declared by the constructor. The function declared in this way will not inherit the scope of the current declaration position. It will only have the global scope by default. However, this is also available in several other function declaration methods, as follows :

function foo() {
  var hi = 'hello';
  //return function() {
  //  alert(hi);
  //};
  return Function('return hi;');
}
foo()(); // 执行效果大家自己跑一下看看

可以想见,用构造函数声明返回的这个函数执行必然报错,因为其作用域(即全局作用域)中没有hi这个变量。

还有一点,就是往往大家要说构造函数方式声明的函数效率要低,这是为什么呢?今天从文档是得知是因为另外3种方式申明的函数只会被解析一次,其实他们存在于闭包中,但是那也只与作用域链有关,函数体是只会被解析一次的。但是构造函数方式呢,每次执行函数的时候,其函数体都会被解析一次,我们可以想想这样声明的函数是一个对象,其中存放了参数以及函数体,每次执行的时候都要先解析一次,参数和函数体,才会执行,这样必然效率低下。具体实验不知道如何做?

最后说一个大家都不怎么注意的地方,什么时候看似函数声明方式的方式却不是函数生命方式(还是这么绕~简单点儿说,就是例2的方式什么时候在不经意间就成其他方式了):

当成为表达式的一部分,就如同例3和例4。
不再是脚本本身或者函数的“源元素”(source element)。什么是源元素呢?即在脚本中的非嵌套语句或者函数体(A "source element" is a non-nested statement in the script or a function body),例如:

var x = 0;        // source element 
if (x == 0) {      // source element 
  x = 10;        // not a source element, 因为嵌套在了if语句里
  function boo() {}   // not a source element, 因为嵌套在了if语句里
} 
function foo() {     // source element 
  var y = 20;      // source element 
  function bar() {}   // source element 
  while (y == 10) {   // source element 
   function blah() {} // not a source element, 因为嵌套在了while语句里
   y++;        // not a source element, 因为嵌套在了while语句里
  } 
}

源元素的概念大概有了理解,继续刚刚说的函数声明,请看:

// 函数声明
function foo() {} 
  
// 函数表达式
(function bar() {}) 
  
// 函数表达式
x = function hello() {} 
 
if (x) { 
  // 函数表达式
  function world() {} 
}
 
// function statement 
function a() { 
  // function statement 
  function b() {} 
  if (0) { 
   // 函数表达式
   function c() {} 
  } 
}

最后这里说一下我自己的理解,之所以要区分函数声明与非函数声明,因为在我看了,函数声明方式的函数定义,在JS解析引擎执行的时候会将其提前声明,也就是像我们刚刚上面说的那样,可以在函数定义之前使用,实际上是解析引擎在我们使用前已经将其解析了,但是非函数声明式,就像表达式函数声明,JS解析引擎只会把var声明的变量提前定义,此时变量值为undefined,而真正对这个变量的赋值是在代码实际所在位置,因此上述提到报错都是undefined,实际变量已经定义了,只是还没有赋值,JS解析引擎不知道它为函数。

相信本文所述对大家javascript WEB程序设计的有一定的借鉴价值。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn