创建函数
function sum(num1, num2) {
return num1 + num2;
}
var sum = function (num1, num2) {
return num1 + num2
}
函数声明和函数表达式
// 函数声明 JavaScript 引擎也能把函数声明提升到顶部
alert(sum(10, 10));
function sum(num1, num2) {
return num1 + num2
}
// 函数表达式 Uncaught TypeError: sum is not a function
alert(sum(10, 10));
var sum = function (num1, num2) {
return num1 + num2;
};
// 作为值的函数
function hanshu(subHanshu,arg) {
return subHanshu(arg)
}
function add10(num) {
return num+10
}
var res1 = hanshu(add10,10)
alert(res1)
函数属性和方法
ECMAScript 中的函数是对象,因此函数也有属性和方法。每个函数都包含两个属性:length 和 prototype。其中,length 属性表示函数希望接收的命名参数的个数。
ECMAScript 核心所定义的全部属性中,prototype 是保存它们所有实例方法的真正所在,例如toString()和 valueOf()等方法实际上都保存在 prototype 名下。
每个函数都包含两个非继承而来的方法:apply()和 call()。用途都是在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。首先,apply()方法接收两个参数:一个是在其中运行函数的作用域,另一个是参数数组。其中,第二个参数可以是 Array 的实例,也可以是arguments 对象。例如:
// apply()第一个参数是this,第二个参数是arguments对象或者数组
function sum(num1, num2) {
return num1 + num2;
}
function callSum1(n1, n2) {
return sum.apply(this, arguments)
}
function callSum2(n3, n4) {
return sum.apply(this, [n3, n4])
}
// call()第一个参数是this,第二个参数逐个列举出来
function callSum3(n5, n6) {
return sum.call(this, n5, n6)
}
alert(callSum1(10, 10))
alert(callSum2(10, 10))
alert(callSum3(15, 20))
// 扩充函数赖以运行的作用域
window.color = "red";
var o = {color: "blue"};
function sayColor() {
alert(this.color);
}
sayColor() //red
sayColor.call(this) //red
sayColor.call(window) //red
sayColor.call(o) //blue
ECMAScript 5 还定义了一个方法:bind()。这个方法会创建一个函数的实例,其 this 值会被绑定到传给 bind()函数的值。例如:
window.color = "red";
var o = { color: "blue" };
function sayColor() {
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor() //blue
基本包装类型
为了便于操作基本类型值,ECMAScript 还提供了 3 个特殊的引用类型:Boolean、Number 和
String。
// var s1 = "some text";
// var s2 = s1.substring(2);
// console.log(s1);
// console.log(s2)
var s1 = new String('some text');
var s2 = s1.substring(2)
s1 = null;
console.log(s2)