Home  >  Article  >  Web Front-end  >  Functions in "JavaScript Adventure"

Functions in "JavaScript Adventure"

高洛峰
高洛峰Original
2016-10-14 09:59:401032browse

A function is a piece of code that is defined only once but can be executed or called any number of times. In JavaScript, functions are objects, and programs can manipulate them at will. For example, you can assign functions to variables, pass them as parameters to other functions, set properties to them, and even call their methods. If a function is mounted on an object as a property of the object, it is called a method of the object. If functions are defined within other functions, they can access any variables in the scope in which they are defined.

Function definition

In JavaScript, functions are actually objects, and each function is an instance of the Function constructor, so the function name is actually a pointer to the function object and will not be bound to a function. Functions are usually defined in the following three ways. For example:

// 写法一:函数声明(推荐写法) 
function sum (num1, num2) { 
    return num1 + num2; 
} 
 
// 写法二:函数表达式(推荐写法) 
var sum = function(num1, num2){ 
    return num1 + num2; 
}; 
 
// 写法三:Function 构造函数(不推荐写法) 
var sum = new Function("num1", "num2", "return num1 + num2");

Since a function name is just a pointer to a function, a function name is no different than any other variable containing a pointer to an object. In other words, a function may have multiple names. For example:

function sum(num1, num2){ 
    return num1 + num2; 
} 
console.log(sum(10,10));        // 20 
 
var anotherSum = sum; 
console.log(anotherSum(10,10)); // 20 
 
sum = null; 
console.log(anotherSum(10,10)); // 20

No overloading

Imagining function names as pointers also helps to understand why there is no concept of function overloading in JavaScript.

function addSomeNumber(num){ 
    return num + 100; 
} 
 
function addSomeNumber(num) { 
    return num + 200; 
} 
 
var result = addSomeNumber(100);    // 300

Obviously, two functions with the same name are declared in this example, and the result is that the later function overwrites the previous function. The above code is actually no different from the code below.

var addSomeNumber = function (num){ 
    return num + 100; 
}; 
 
addSomeNumber = function (num) { 
    return num + 200; 
}; 
 
var result = addSomeNumber(100);    // 300

After rewriting the code, it is easy to understand that when creating the second function, the variable addSomeNumber that references the first function is actually overwritten.

Function declaration and function expression

The parser does not treat "function declaration" and "function expression" equally when loading data into the execution environment. The parser will first read the function declaration and make it available (accessible) before executing any code; as for the function expression, it will not be actually interpreted and executed until the parser reaches the line of code where it is located. For example:

console.log(sum(10,10)); // 20 
function sum(num1, num2){ 
    return num1 + num2; 
}

The above code can run normally. Because before the code starts executing, the parser has already read and added the function declaration to the execution environment through a process called function declaration hoisting. When evaluating code, the JavaScript engine declares functions on the first pass and places them at the top of the source tree. So, even if the code that declares the function is behind the code that calls it, the JavaScript engine can hoist the function declaration to the top. Changing the above "function declaration" to the equivalent "function expression" will cause an error during execution. For example:

console.log(sum(10,10)); // Uncaught TypeError: sum is not a function 
var sum = function(num1, num2){ 
    return num1 + num2; 
};

In addition to the above differences, the syntax of "function declaration" and "function expression" are equivalent.

Function as value

Because the function name itself in JavaScript is a variable, the function can also be used as a value. That is, not only can you pass a function to another function like a parameter, but you can also return a function as the result of another function. Let’s take a look at the following function.

function callSomeFunction(someFunction, someArgument){ 
    return someFunction(someArgument); 
}

This function accepts two parameters. The first parameter should be a function and the second parameter should be a value to be passed to the function. Then, you can pass the function as in the example below.

function add10(num){ 
    return num + 10; 
} 
 
var result1 = callSomeFunction(add10, 10); 
console.log(result1);   // 20 
 
function getGreeting(name){ 
    return "Hello, " + name; 
} 
 
var result2 = callSomeFunction(getGreeting, "Nicholas"); 
console.log(result2);   // "Hello, Nicholas"

The callSomeFunction() function here is universal, that is, no matter what function is passed in as the first parameter, it will return the result of executing the first parameter. To access a function pointer without executing the function, you must remove the pair of parentheses after the function name. Therefore, add10 and getGreeting are passed to callSomeFunction() in the above example, not the results after executing them.

Of course, you can also return another function from one function, and this is also an extremely useful technique. For example, suppose we have an array of objects and we want to sort the array based on some object property. The comparison function passed to the array sort() method receives two parameters, the values ​​to be compared. However, we need a way to specify which attribute to sort by. To solve this problem, you can define a function that receives an attribute name and then creates a comparison function based on the attribute name. The following is the definition of this function.

function createComparisonFunction(propertyName) { 
    return function(object1, object2){ 
        var value1 = object1[propertyName]; 
        var value2 = object2[propertyName]; 
        if (value1 < value2){ 
            return -1; 
        } else if (value1 > value2){ 
            return 1; 
        } else { 
            return 0; 
        } 
    }; 
}

This function definition looks a bit complicated, but in fact it is nothing more than nesting another function within a function, and a return operator is added in front of the inner function. After the inner function receives the propertyName parameter, it uses square bracket notation to get the value of the given property. After obtaining the desired attribute value, defining the comparison function is very simple. The above function can be used like in the example below.

var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age: 29}]; 
 
data.sort(createComparisonFunction("name")); 
console.log(data[0].name);  // Nicholas 
 
data.sort(createComparisonFunction("age")); 
console.log(data[0].name);  // Zachary

这里,我们创建了一个包含两个对象的数组 data。其中,每个对象都包含一个 name 属性和一个 age 属性。在默认情况下,sort() 方法会调用每个对象的 toString() 方法以确定它们的次序;但得到的结果往往并不符合人类的思维习惯。因此,我们调用 createComparisonFunction("name") 方法创建了一个比较函数,以便按照每个对象的 name 属性值进行排序。而结果排在前面的第一项是 name 为 "Nicholas",age 是 29 的对象。然后,我们又使用了 createComparisonFunction("age") 返回的比较函数,这次是按照对象的age属性排序。得到的结果是 name 值为 "Zachary",age 值是 28 的对象排在了第一位。

函数的形参和实参

在函数内部,有两个特殊的对象:arguments 和 this。其中,arguments 是一个类数组对象,包含着传入函数中的所有参数。虽然arguments 的主要用途是保存函数参数,但这个对象还有一个名叫 callee 的属性,该属性是一个指针,指向拥有这个 arguments对象的函数。请看下面这个非常经典的阶乘函数。

function factorial(num){ 
if (num <= 1) { 
        return 1; 
    } else { 
        return num * factorial(num-1) 
    } 
}

定义阶乘函数一般都要用到递归算法,如上面的代码所示,在函数有名字,而且名字以后也不会变的情况下,这样定义没有问题。但问题是这个函数的执行与函数名 factorial 紧紧耦合在了一起。为了消除这种紧密耦合的现象,可以像下面这样使用arguments.callee。

function factorial(num){ 
    if (num <=1) { 
        return 1; 
    } else { 
        return num * arguments.callee(num-1) 
    } 
}

在这个重写后的 factorial() 函数的函数体内,没有再引用函数名 factorial。这样,无论引用函数时使用的是什么名字,都可以保证正常完成递归调用。例如:

var trueFactorial = factorial; 
 
factorial = function(){ 
    return 0; 
}; 
 
console.log(trueFactorial(5));  // 120 
console.log(factorial(5));      // 0

在此,变量 trueFactorial 获得了 factorial 的值,实际上是在另一个位置上保存了一个函数的指针。然后,我们又将一个简单地返回 0 的函数赋值给 factorial 变量。如果像原来的 factorial() 那样不使用 arguments.callee,调用 trueFactorial() 就会返回 0。可是,在解除了函数体内的代码与函数名的耦合状态之后,trueFactorial() 仍然能够正常地计算阶乘;至于factorial(),它现在只是一个返回 0 的函数。

函数内部的另一个特殊对象是 this,其行为与 Java 和 C# 中的 this 大致类似。换句话说,this 引用的是函数据以执行的环境对象(当在网页的全局作用域中调用函数时,this 对象引用的就是 window)。来看下面的例子。

window.color = "red"; 
var o = { color: "blue" }; 
 
function sayColor(){ 
    console.log(this.color); 
} 
sayColor();     // "red" 
 
o.sayColor = sayColor; 
o.sayColor();   // "blue"

上面这个函数 sayColor() 是在全局作用域中定义的,它引用了 this 对象。由于在调用函数之前,this 的值并不确定,因此this 可能会在代码执行过程中引用不同的对象。当在全局作用域中调用 sayColor() 时,this 引用的是全局对象 window;换句话说,对 this.color 求值会转换成对 window.color 求值,于是结果就返回了 "red"。而当把这个函数赋给对象 o 并调用o.sayColor() 时,this 引用的是对象 o,因此对 this.color 求值会转换成对 o.color 求值,结果就返回了 "blue"。

请大家一定要牢记,函数的名字仅仅是一个包含指针的变量而已。因此,即使是在不同的环境中执行,全局的 sayColor() 函数与o.sayColor() 指向的仍然是同一个函数。

ECMAScript 5也规范化了另一个函数对象的属性 caller。这个属性中保存着「调用当前函数的函数的引用」,如果是在全局作用域中调用当前函数,它的值为 null。例如:

function outer(){ 
    inner(); 
} 
 
function inner(){ 
    console.log(arguments.callee.caller); 
}  
 
outer();

以上代码会导致警告框中显示 outer() 函数的源代码。因为 outer() 调用了 inter(),所以 arguments.callee.caller 就指向outer()。

在严格模式下,访问 arguments.callee属性,或为函数的 caller 属性赋值,都会导致错误。

函数的属性和方法

JavaScript 中的函数是对象,因此函数也有属性和方法。每个函数都包含两个属性:length 和 prototype。其中,length 属性表示函数希望接收的命名参数的个数,如下面的例子所示。

function sayName(name){ 
    console.log(name); 
} 
 
function sum(num1, num2){ 
    return num1 + num2; 
} 
 
function sayHi(){ 
    console.log("hi"); 
} 
 
console.log(sayName.length);      // 1 
console.log(sum.length);          // 2 
console.log(sayHi.length);        // 0

对于 JavaScript 中的引用类型而言,prototype 是保存它们所有实例方法的真正所在。换句话说,诸如 toString() 和 valueOf()等方法实际上都保存在 prototype 名下,只不过是通过各自对象的实例访问罢了。在创建自定义引用类型以及实现继承时,prototype 属性的作用是极为重要的。在 ECMAScript 5中,prototype 属性是不可枚举的,因此使用 for-in 无法发现。

每个函数都包含两个非继承而来的方法:apply() 和 call()。这两个方法的用途都是在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。首先,apply() 方法接收两个参数:一个是在其中运行函数的作用域,另一个是参数数组。其中,第二个参数可以是 Array 的实例,也可以是 arguments 对象。例如:

function sum(num1, num2){ 
    return num1 + num2; 
} 
 
function callSum1(num1, num2){ 
    return sum.apply(this, arguments);  // 传入 arguments 对象 
} 
 
function callSum2(num1, num2){ 
    return sum.apply(this, [num1, num2]);  // 传入数组 
} 
 
console.log(callSum1(10,10));   // 20 
console.log(callSum2(10,10));   // 20

在上面这个例子中,callSum1() 在执行 sum() 函数时传入了 this(因为是在全局作用域中调用的,所以传入的就是 window 对象)和 arguments 对象。而 callSum2 同样也调用了 sum() 函数,但它传入的则是 this 和一个参数数组。这两个函数都会正常执行并返回正确的结果。

call() 方法与 apply() 方法的作用相同,它们的区别仅在于接收参数的方式不同。对于 call() 方法而言,第一个参数是 this 值没有变化,变化的是其余参数都直接传递给函数。换句话说,在使用 call() 方法时,传递给函数的参数必须逐个列举出来,如下面的例子所示。

function sum(num1, num2){ 
    return num1 + num2; 
} 
 
function callSum(num1, num2){ 
    return sum.call(this, num1, num2); 
} 
 
console.log(callSum(10,10));   // 20

在使用 call() 方法的情况下,callSum() 必须明确地传入每一个参数。结果与使用 apply() 没有什么不同。至于是使用 apply()还是 call(),完全取决于你采取哪种给函数传递参数的方式最方便。如果你打算直接传入 arguments 对象,或者包含函数中先接收到的也是一个数组,那么使用 apply() 肯定更方便;否则,选择 call() 可能更合适。(在不给函数传递参数的情况下,使用哪个方法都无所谓。)

事实上,传递参数并非 apply() 和 call() 真正的用武之地;它们真正强大的地方是能够扩充函数赖以运行的作用域。下面来看一个例子。

window.color = "red"; 
var o = { color: "blue" }; 
 
function sayColor(){ 
    console.log(this.color); 
} 
sayColor();                // red 
 
sayColor.call(this);       // red 
sayColor.call(window);     // red 
sayColor.call(o);          // blue

这个例子是在前面说明 this 对象的示例基础上修改而成的。这一次,sayColor() 也是作为全局函数定义的,而且当在全局作用域中调用它时,它确实会显示 "red",因为对 this.color 的求值会转换成对 window.color 的求值。而 sayColor.call(this) 和sayColor.call(window),则是两种显式地在全局作用域中调用函数的方式,结果当然都会显示 "red"。但是,当运行sayColor.call(o) 时,函数的执行环境就不一样了,因为此时函数体内的 this 对象指向了 o,于是结果显示的是 "blue"。

使用 call() 或 apply() 来扩充作用域的最大好处,就是对象不需要与方法有任何耦合关系。在前面例子的第一个版本中,我们是先将 sayColor() 函数放到了对象 o 中,然后再通过 o 来调用它的;而在这里重写的例子中,就不需要先前那个多余的步骤了。

关卡

// 挑战一,合并任意个数的字符串 
var concat = function(){ 
    // 待实现方法体 
} 
console.log(concat(&#39;st&#39;,&#39;on&#39;,&#39;e&#39;));  // stone 
// 挑战二,输出指定位置的斐波那契数列 
var fioacciSequece = function(count){ 
    // 待实现方法体 
} 
console.log(fioacciSequece(12));  // 0、1、1、2、3、5、8、13、21、34、55、89 
// 挑战三,三维数组或 n 维数组去重,使用 arguments 重写 
var arr = [2,3,4,[2,3,[2,3,4,2],5],3,5,[2,3,[2,3,4,2],2],4,3,6,2]; 
var unique = function(arr){ 
    // 待实现方法体 
} 
console.log(unique(arr)); // [2,3,4,5,6]


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