JavaScript中定义function有以下三种方式

(1)声明一个表达式变量,并定义该变量的表达式。如:

var func = function()
{
      
/*body code*/
}

(2) 定义一个function表达式,并指定该表达式的标识。如:

function func()
{
      
//body code
}

(3) 使用JavaScript内置Function对象构造。如:

var func = new Function("/*parameters*/","/*body code*/");

声明变量定义与使用function表达式标识定义是有区别的。我们知道,function在发生传递时采用的是引用传递类型,使用变量定义是保存了表达式的地址引用,而使用标志定义保存了表达式的地址。因此当我们改变或重新定义变量时,并不会导致原来的表达式改变;而当改变标识时,其对应的表达式也随之改变。如:

()
{
      alert("reference test");
}

//定义一个表达式,保存其地址信息于test1中
function test1()
{
      alert(
"reference test1");
}

//将test所引用的表达式传递给reference
var reference = test;
//将test1表达式的地址传递给reference1
var reference1 = test1;

//改变变量test的引用
test = function()
{
      alert(
"new test");
}

//重新定义test1地址内的数据
function test1()
{
      alert(
"new test1");
}

alert(reference);
//其所引用的表达式不改变
alert(reference1);//由于reference1是test1地址的引用,当test1地址表示的内容改变时,reference1的内容也随之改变

相关文章: