我需要将参数作为真实参数传递给回调函数.我怎么做?回调需要可变数量的参数.
示例函数如下:
var func = function (callback) {
doSomething(function () {
// the goal is to pass on the arguments object to the callback function as real arguments
callback(arguments)
});
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
它可能是一个类似的问题: 是否可以向JavaScript函数发送可变数量的参数?
但我不明白这个问题,也不理解答案.
编辑:如果可能的话,我想不污染全球.
我想做一个像这样的功能.
例如:
function Logger() {
this.log = function(msg) {
console.log(msg);
}
}
Run Code Online (Sandbox Code Playgroud)
我想在功能/模块等中使用它,一切正常.但是浏览器中的默认控制台通常会给出fileName + lineNumber.
现在,当我抽象此功能,fileName而lineNumber不是在这里我把我的instance.log().因为它会说调用console.log的地方,而不是函数本身.
所以我的问题:
如何从我想要使用记录器的位置获取正确的信息?或者,请给我任何改进此功能的提示.
在下面的代码中,我可以使用print代替console.log,程序可以正常运行.但是我希望使用console.log但是我得到了
非法调用
在运行时
function forEach(array, action) {
for (var i=0; i<array.length; i++)
action(array[i]);
}
forEach(["blah", "bac"], console.log);
Run Code Online (Sandbox Code Playgroud) 我有一个功能:
var doThis = function(callback){
callback('google.com');
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做,它的工作原理:
doThis(alert);
Run Code Online (Sandbox Code Playgroud)
但如果我这样做,我会收到一个错误:
doThis(window.location.replace);
Run Code Online (Sandbox Code Playgroud)
未捕获的TypeError:非法调用
我正在为AJAX调用构建一个包装器,我需要支持alert自定义函数等函数window.location.replace.我究竟做错了什么?
而是一个关于javascript事件的技术问题:
为什么
window.onmousewheel = console.log;
Run Code Online (Sandbox Code Playgroud)
扔了Uncaught TypeError: Illegal invocation,而
window.onmousewheel = function (e) {console.log(e); };
Run Code Online (Sandbox Code Playgroud)
按预期工作并将事件打印为字符串?为什么console.log在分配时window.onmousewheel,不仅仅使用lambda表达式之类的参数调用?
西蒙
我有javascript代码,如果它在浏览器中运行会引发警报,但是当我运行单元测试时我不想提出警报.
我试着用一条线来解决这个问题
if( allowAlerts === false ){
alert = console.log;
}
Run Code Online (Sandbox Code Playgroud)
但是当我跑的时候
alert("This bad thing happened");
Run Code Online (Sandbox Code Playgroud)
我回来了
TypeError: Illegal invocation
Run Code Online (Sandbox Code Playgroud)
直接重新分配警报是一个kludgey解决方案,我可以通过其他方式轻松解决问题,但我以前从未遇到过非法调用错误,并希望有人能够解释它的含义.
我有一个javascript文件,这是一个简写为console.log,
var log = console.log
log("this message is logged with shortened keyword")
Run Code Online (Sandbox Code Playgroud)
在运行时,它会抛出错误,
Uncaught TypeError: Illegal invocation
Run Code Online (Sandbox Code Playgroud)
Jsfiddle ---- https://jsfiddle.net/w42vp7zg/