JSlint错误'不要在循环中创建函数'。引出有关Javascript本身的问题 [英] JSlint error 'Don't make functions within a loop.' leads to question about Javascript itself

查看:111
本文介绍了JSlint错误'不要在循环中创建函数'。引出有关Javascript本身的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码在循环中调用匿名函数,类似于这个伪示例:

I have some code that invokes anonymous functions within a loop, something like this pseudo example:

for (i = 0; i < numCards; i = i + 1) {
    card = $('<div>').bind('isPopulated', function (ev) {
        var card = $(ev.currentTarget);
        ....

JSLint报告错误'不要制作循环中的函数。'我喜欢保持我的代码JSLint干净。我知道我可以将匿名函数移出循环并将其作为命名函数调用。除此之外,这是我的问题:

JSLint reports the error 'Don't make functions within a loop.' I like to keep my code JSLint clean. I know I can move the anonymous function out of the loop and invoke it as a named function. That aside, here's my question:

Javascript解释器是否真的会为每次迭代创建一个函数实例?或者实际上只有一个函数实例已编译并且重复执行相同的代码?也就是说,JSLint是否建议到将函数移出循环实际上会影响代码的效率吗?

Would a Javascript interpreter really create an instance of the function per iteration? Or is there really only one function instance "compiled" and the same code is executed repeatedly? That is, does the JSLint "suggestion" to move the function out of the loop actually affect the efficiency of the code?

推荐答案


会不会是一个Javascript间preter真的每次迭代创建一个函数实例吗?

Would a Javascript interpreter really create an instance of the function per iteration?

它必须因为它不知道函数对象是否会被修改别处。请记住,函数是标准JavaScript对象,因此它们可以具有与任何其他对象类似的属性。执行此操作时:

It has to because it doesn't know if the function object will be modified elsewhere. Remember that functions are standard JavaScript objects, so they can have properties like any other object. When you do this:

card = $('<div>').bind('isPopulated', function (ev) { ... })

如你所知, bind 可以修改对象,例如:

for all you know, bind could modify the object, for example:

function bind(str, fn) {
  fn.foo = str;
}

显然,如果在所有迭代中共享函数对象,这将导致错误的行为。

Clearly this would result in wrong behaviour if the function object was shared across all iterations.

这篇关于JSlint错误'不要在循环中创建函数'。引出有关Javascript本身的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆