jQuery v1.7.2
我有这个功能在执行时给我以下错误:
Uncaught TypeError: Illegal invocation
Run Code Online (Sandbox Code Playgroud)
这是功能:
$('form[name="twp-tool-distance-form"]').on('submit', function(e) {
e.preventDefault();
var from = $('form[name="twp-tool-distance-form"] input[name="from"]');
var to = $('form[name="twp-tool-distance-form"] input[name="to"]');
var unit = $('form[name="twp-tool-distance-form"] input[name="unit"]');
var speed = game.unit.speed($(unit).val());
if (!/^\d{3}\|\d{3}$/.test($(from).val()))
{
$(from).css('border-color', 'red');
return false;
}
if (!/^\d{3}\|\d{3}$/.test($(to).val()))
{
$(to).css('border-color', 'red');
return false;
}
var data = {
from : from,
to : to,
speed : speed
};
$.ajax({
url : base_url+'index.php',
type: 'POST',
dataType: 'json',
data: data,
cache : false
}).done(function(response) {
alert(response);
});
return false; …Run Code Online (Sandbox Code Playgroud) 我记得,当我想console.log作为一个回调参数传递给某个函数时,除非我使用该bind()方法绑定console它,否则它不起作用.
例如:
const callWithTest = callback => callback('test');
callWithTest(console.log); // That didn't use to work.
callWithTest(console.log.bind(console)); // That worked (and works) fine.
Run Code Online (Sandbox Code Playgroud)
请参阅未捕获的TypeError:javascript中的非法调用.
但是,最近我发现console.log()即使调用除控制台以外的对象,它也能正常工作.例如:
console.log.call(null, 'test');
Run Code Online (Sandbox Code Playgroud)
日志'test'.
它何时以及为何会改变?规范是否说明了什么?
我对此感到困惑.请找到如下代码.
var o={
printToConsole: function(f){
f(1);
}
};
o.printToConsole(console.log);
Run Code Online (Sandbox Code Playgroud)
//TypeError: Illegal invocation//我得到一个TypeError
从console.log的定义我们得到了这个
`function log() { [native code] }`
Run Code Online (Sandbox Code Playgroud)
在chrome中,它清楚地显示它不需要任何参数,但是当我们尝试在控制台上打印东西时,我们会这样写,即将参数传递给console.log.
console.log('Take me on Console');
Run Code Online (Sandbox Code Playgroud)
为什么我得到这个TypeError以及这个console.log在chrome中的行为?
而是一个关于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表达式之类的参数调用?
西蒙
当我尝试
[1,2,3].forEach(alert);
Run Code Online (Sandbox Code Playgroud)
它会按预期打开数组中每个项目的消息框.
但是,当我尝试
[1,2,3].forEach(console.log);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Uncaught TypeError: Illegal invocation
Run Code Online (Sandbox Code Playgroud)
为什么?
我有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解决方案,我可以通过其他方式轻松解决问题,但我以前从未遇到过非法调用错误,并希望有人能够解释它的含义.