1. with
一种闭包,其基本语法是:
with (object) {
statement
}
with会扩展statement代码块中的作用域链scope chain,把参数对象加入到{}代码块执行环境(execution context)里面的作用域链(scope chain)的首部,会修改索引对象的顺序。一个简单例子:
x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10)
y = Math.tan(14 * Math.E)
with (Math){
x = cos(3 * PI) + sin (LN10)
y = tan(14 * E)
}
2. arguments
function 的隐含参数,表示正在执行的函数和调用它的函数的参数,可以通过类似访问数组的方式访问function的所有参数。一个简单例子:格式化一个字符串的函数。
function format(string) {
var args = arguments;
var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
return String(string).replace(pattern, function(match, index) {
return args[index];
});
};
format("And the %1 want to know whose %2 you %3″, "papers", "shirt", "wear");
3.caller
function 属性,返回一个对函数的引用,该函数调用了当前函数。msdn里的解释:
caller 属性只有当函数正在执行时才被定义。 如果函数是从 JavaScript 程序的顶层调用的,则 caller 包含 null。 如果在字符串上下文中使用 caller 属性,则其结果和 functionName.toString 相同,也就是说,将显示函数的反编译文本。一个例子:
function callerDemo() {
if (callerDemo.caller) {
var a= callerDemo.caller.toString();
alert(a);
} else {
alert("this is a top function");
}
}
function handleCaller() {
callerDemo();
}
callerDemo() 与 handleCaller()这两种调用方式是不同的。
4. callee
返回正被执行的 Function 对象,也就是所指定的 Function 对象的正文。
[function.]arguments.callee。可选项 function 参数是当前正在执行的 Function 对象的名称。
callee 属性的初始值就是正被执行的 Function 对象。callee 属性是 arguments 对象的一个成员,它表示对函数对象本身的引用,这有利于匿名函数的递归或者保证函数的封装性。arguments.length是实参长度,arguments.callee.length是形参长度。arguments.callee(XX) 可以对匿名函数的调用,一个简单例子:
var sum = function(n){
if (n <= 0)
return 1;
else
return n +arguments.callee(n - 1)
} //递归....
5. call、apply
call, apply都属于Function.prototype的一个方法,它是JavaScript引擎内在实现的,因为属于Function.prototype,所以每个Function对象实例,也就是每个方法都有call, apply属性。 这两个关键字一般都是一起讨论,他们实现的功能是一致的,只是传递的参数不同,都是将函数绑定到另外一个对象上去运行,改变函数的运行时环境
foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)
一个简单例子:
function print(a, b, c, d){
alert(a + b + c + d);
}
function example(a, b , c , d){
//用call方式借用print,参数显式打散传递
print.call(this, a, b, c, d);
//用apply方式借用print, 参数作为一个数组传递,
//这里直接用JavaScript方法内本身有的arguments数组
print.apply(this, arguments);
//或者封装成数组
print.apply(this, [a, b, c, d]);
}
//下面将显示”背光脚本”
example(”背” , “光” , “脚”, “本”);
6.bind
对于给定函数,创建具有与原始函数相同的主体的绑定函数。 绑定函数的 this 对象与指定对象关联并具有指定的初始参数。
function.bind(thisArg[,arg1[,arg2[,argN]]])
简单例子:
// Define the original function.
var checkNumericRange = function (value) {
if (typeof value !== 'number')
return false;
else
return value >= this.minimum && value <= this.maximum;
}
// The range object will become the this value in the callback function.
var range = { minimum: 10, maximum: 20 };
// Bind the checkNumericRange function.
var boundCheckNumericRange = checkNumericRange.bind(range);
// Use the new function to check whether 12 is in the numeric range.
var result = boundCheckNumericRange (12);
document.write(result);
// Output: true