Strict-Mode:argument.callee.length的替代方法
Strict-Mode: Alternative to argument.callee.length?
Javascript: The Definitive Guide (2011) 有这个例子(p.186),它在严格模式下不起作用,但没有展示如何在严格模式下实现它 - 我可以想到要尝试的事情,但我想知道最佳实践/安全性/性能 - 在严格模式下做这种事情的最佳方法是什么? 代码如下:
// This function uses arguments.callee, so it won't work in strict mode.
function check(args) {
var actual = args.length; // The actual number of arguments
var expected = args.callee.length; // The expected number of arguments
if (actual !== expected) // Throw an exception if they differ.
throw Error("Expected " + expected + "args; got " + actual);
}
function f(x, y, z) {
check(arguments); // Check that the actual # of args matches expected #.
return x + y + z; // Now do the rest of the function normally.
}
您可以传递正在检查的函数。
function check(args, func) {
var actual = args.length,
expected = func.length;
if (actual !== expected)
throw Error("Expected " + expected + "args; got " + actual);
}
function f(x, y, z) {
check(arguments, f);
return x + y + z;
}
或者,如果您所处的环境允许,请延长Function.prototype
...
Function.prototype.check = function (args) {
var actual = args.length,
expected = this.length;
if (actual !== expected)
throw Error("Expected " + expected + "args; got " + actual);
}
function f(x, y, z) {
f.check(arguments);
return x + y + z;
}
或者你可以做一个装饰器函数,它返回一个将自动执行检查的函数......
function enforce_arg_length(_func) {
var expected = _func.length;
return function() {
var actual = arguments.length;
if (actual !== expected)
throw Error("Expected " + expected + "args; got " + actual);
return _func.apply(this, arguments);
};
}
。并像这样使用它...
var f = enforce_arg_length(function(x, y, z) {
return x + y + z;
});
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 数组在递归方法中设置为null
- 打破承诺链的好方法是什么
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 使用“;这个“;JavaScript原型方法中的关键字
- 序列化数据属性中对象的最可靠方法
- 使用Objective-C的JavaScript注入方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 有没有一种方法可以防止img get请求使用css或js发生
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- toBoolean方法类似于toString
- 如何在单击复选框后调用控制器方法
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- TypeError:在不兼容的接收器nodejs上调用了方法Uint8Array.length
- jquery .val() 和 .length 方法无法按预期工作
- JavaScript files.length 在 ie9 中不起作用需要替代方法
- Strict-Mode:argument.callee.length的替代方法
- JavaScript length方法总是为json对象返回1
- 为什么.length不是一个需要()的方法