IE10 Javascript“预期功能”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20192198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:59:26  来源:igfitidea点击:

IE10 Javascript "Function Expected"

javascriptfunctioninternet-explorer

提问by d0c_s4vage

This code is giving me a SCRIPT5002: Function expectederror:

这段代码给了我一个SCRIPT5002: Function expected错误:

var callIt = function(func) { func(); }

WHY!? It's like it's trying to do type checking or something

为什么!?就像它正在尝试进行类型检查或其他什么

EDIT: use case

编辑:用例

var callIt = function(func) { func(); }
function nextSlide() {
    var fn = currSlide ? currSlide.hide : callIt;
    currSlide = setupSlides[++slideIdx];
    fn(currSlide.show());
}

DOH!

哦!

回答by T.J. Crowder

Your code:

您的代码:

fn(currSlide.show());

...callscurrSlide.show()and passes the return value from calling it into fn, exactly the way foo(bar())callsbarand passes its return value into foo.

...调用currSlide.show()并将返回值从调用中传递到 中fn,与foo(bar())调用bar并将其返回值传递到 中的方式完全相同foo

since the return value of showis not a function, you get the error. You may have meant:

由于的返回值show不是函数,因此您会收到错误消息。你的意思可能是:

fn(function() { currSlide.show(); });


Note, though, that you have a problem here:

但是请注意,您在这里遇到了问题:

var fn = currSlide ? currSlide.hide : callIt;

If currSlideis truthy, you'll get a reference to the hidefunction, but that function is notin any way connected to currSlide. If you call it later, it's likely to fail because it's expecting thisto mean something specific.

如果currSlide是truthy,你会得到的一个参考hide作用,但功能并不在连接到任何方式currSlide。如果你稍后调用它,它可能会失败,因为它期望this表示特定的东西。

If you can rely on having the features from ECMAScript5 (so, you're using a modern browser other than IE8 and/or you're including an "es5 shim", you can fix that with Function#bind:

如果您可以依赖 ECMAScript5 的功能(因此,您使用的是 IE8 以外的现代浏览器和/或您包含了“es5 shim”,您可以使用以下命令修复它Function#bind

var fn = currSlide ? currSlide.hide.bind(currSlide) : callIt;

Or if you're using jQuery, you can fix it with jQuery's $.proxy:

或者,如果您使用 jQuery,则可以使用 jQuery 修复它$.proxy

var fn = currSlide ? $.proxy(currSlide.hide, currSlide) : callIt;

Both of those return a new function that, when called, will call the target function with the given thisvalue.

这两个函数都返回一个新函数,当调用该函数时,将使用给定this值调用目标函数。

If you're not using ES5 or jQuery, well, this would do it:

如果您不使用 ES5 或 jQuery,那么可以这样做:

var prevSlide = currSlide;
var fn = prevSlide ? function(func) { prevSlide.hide(func); } : callIt;

...but at that point I suspect stepping back and reevaluating might be in order.

...但那时我怀疑退后一步重新评估可能是合适的。