这只是出于好奇,但是你们中的任何人都知道为什么这段代码不起作用?
[1, 2, 3, 4, 5].forEach(console.log);
// Prints 'Uncaught TypeError: Illegal invocation' in Chrome
Run Code Online (Sandbox Code Playgroud)
另一方面,这似乎工作正常:
[1, 2, 3, 4, 5].forEach(function(n) { console.log(n) });
Run Code Online (Sandbox Code Playgroud)
那么......?
this在对象原型中存储的事件处理程序中保留javascript引用的正确方法是什么?我想远离创建像'_this'或'that'这样的临时变量,我不能使用像jQuery这样的框架.我看到很多人谈论使用'绑定'功能但不确定如何在我给定的场景中实现它.
var Example = function(foo,bar){
this.foo = foo;
this.bar = bar;
};
Example.prototype.SetEvent = function(){
this.bar.onclick = this.ClickEvent;
};
Example.prototype.ClickEvent = function(){
console.log(this.foo); // logs undefined because 'this' is really 'this.bar'
};
Run Code Online (Sandbox Code Playgroud) 我想将一个参数传递给一个名为using的函数setTimeout.我找到了这三个选项:
A = 1;
// Method 1: closure things
setTimeout(function() { whatsA(A); }, 100);
// Method 2: third argument (same result with [A])
setTimeout(whatsA, 100, A);
// Method 3: eval
setTimeout('whatsA(' + A + ')', 100);
A = 2;
function whatsA(X) { console.log(X); }
Run Code Online (Sandbox Code Playgroud)
这在Internet Explorer 9中显示2,undefined和1.
方法1:显然,我不希望在传递之后更改参数(当然在简单整数的情况下).
方法2:如果只有Internet Explorer支持它,这将是完美的.
方法3:这似乎是唯一的选择.但它看起来并不像其他人那么漂亮,传递的东西要被评估而不是功能.
有没有更好的办法?
我试图理解这段代码的奇怪行为:
window.setTimeout(window.location.reload, 200);
Run Code Online (Sandbox Code Playgroud)
在Firefox中,这会引发TypeError:
TypeError:在未实现接口Location的对象上调用'reload'.
在Chromium中,这会引发另一个TypeError:
未捕获的TypeError:非法调用
这两种选择工作正常:
window.setTimeout('window.location.reload()', 200);window.setTimeout(function(){window.location.reload()}, 200)为什么?
javascript ×4
settimeout ×2
arrays ×1
closures ×1
foreach ×1
function ×1
oop ×1
scope ×1
this ×1