Home Web Front-end JS Tutorial Summary of several differences in javascript function definition_javascript skills

Summary of several differences in javascript function definition_javascript skills

May 16, 2016 pm 05:05 PM
javascript function

javascript函数的定义

1:调用关键字function来构造,如:
function distance(x1,x2,y1,y2)
{
var dx=x2-x1;
var dy=y2-y1;
return Math.sqrt(dx*dx+dy*dy);
}

2:使用Function()构造函数
var f=new Function*"x","y","return x*y");
这行代码创建了一个新函数,该函数和你所熟悉的语法定义的函数基本上时等价的:

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

Functino()构造函数可以接受任意多个字符串参数。它的最后一个参数时函数的主体,其中可以包含任何JavaScript语句,语句之间用分号分隔。其他的参数都是用来说明函数要定义的形式参数名的字符串。如果你定义的函数没有参数,那么可以只需给构造函数传递一个字符串(即函数的主体)即可。

注意,传递给构造函数Function()的参数中没有一个用于说明它要创建的函数名。用Function()构造函数创建的未命名函数有时被成为“匿名函数”。

你可能非常想知道Function()构造函数的用途是什么。为什么不能只用function语句来定义所有的函数呢?原因是Function()构造函数允许我们动态地建立和编译一个函数,它不会将我们限制在function语句预编译的函数体中。这样做带来的负面影响效应就是每次调用一个函数时,Function()构造函数都要对它进行编译。因此,在循环体中或者在经常使用的函数中,我们不应该频繁地调用这个构造函数。

使用Function()构造函数的另一个原因是它能够将函数定义为JavaScript表达式的一部分,而不是将其定义一个语句,这种情况下使用它就显得比较的方面,甚至可以说精致。

3:函数直接量
函数直接量是一个表达式,它可以定义匿名函数。函数直接量的语法和function语句非常相似,只不过它被用作表达式,而不是用作语句,而且也无需指定函数名。下面的三行代码分别使用function()语句、Funciont()构造函数和函数直接量定义了三个基本上相同的函数:

function f(x){return x*x};
var f=new Function("x","return x*x;");
var f=function(x){reurn x*x};

虽然函数直接量创建的是未命名函数,但是它的语法也规定它可以指定函数名,这在编写调用自身的递归函数时非常有用。例如:
var f=function fact(x){if(x<=1)return 1;else return x*fact(x-1);};
上面的代码定义了一个未命名函数,并对它的引用存储在变量f中。它并没有真正的创建一个名为fact()的函数,只是允许函数体用这个名字来引用自身。但是要注意,JavaScript1.5之前的版本中没有正确实现这种命名的函数直接量。

函数直接量的用法和用Function()构造函数创建函数的方法非常相似。由于它们都是由JavaScript的表达式创建的,而不是由语句创建的,所以使用它们的方式也就更加灵活,尤其适用于那些只使用一次,而且无需命名的函数。例如,一个使用函数直接量表达式指定的函数可以存储在一个变量中、传递给其他的函数甚至被直接调用:

a[0]=function(x){return x*x;};//定义一个函数并保存它
a.sort(function(a,b){return a-b;});//定义一个函数;把它传递给另一个函数
var tensquared=(function(x){return x*x;})(10);

和Function()构造函数一样,函数直接量创建的是未命名函数,而且不会自动地将这个函数存储在属性中。但是,比起Function()构造函数来说,函数直接量有一个重要的优点。由Function()构造函数创建的函数的主体必须用一个字符串说明,用这种方式来表达一个长而复杂的函数是狠笨拙的。但是函数直接量的主体使用的却是标准的JavaScript语法。而且函数直接量只被解析一次,而作为字符串传递给Function()构造函数的 JavaScript代码则在每次调用构造函数时只需被解析一次和编译一次。

在JavaScript1.1中,可以使用构造函数Function()来定义函数,在JavaScript1.2和其后的版本中,还可以使用函数直接量来构造函数。你应该注意这两种方法之间的重要差别。

First, the constructor Function() allows JavaScript code to be dynamically created and compiled at runtime. But function literals are a static part of the function structure, just like the function statement.

Secondly, as a corollary to the first difference, each time the constructor Function() is called, the function body will be parsed and a new Eastern Han numeral object will be created. This approach is very inefficient if the call to the constructor occurs in a loop or in a frequently called function. On the other hand, function literals or nested functions that appear within loops and functions are not recompiled on each call, and a new function object is not created each time a function literal is encountered.

The third difference between Function() constructors and functions is that functions created using the constructor Function() do not use lexical scope. Instead, they are always treated as top-level function to compile, as illustrated by the following code:

var y="global";
function constructFunction()
{
var y="local";
return new Function("return y");//Do not capture local effects domain.
}
//This line of code will display "global" because the function returned by the Function() constructor does not use local scope.
//If a function literal is used, this line of code may display "local".
alert(constructFunction());

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles