为什么要调用该函数?JavaScript/视窗 [英] Why is the function called? JavaScript / Window

查看:58
本文介绍了为什么要调用该函数?JavaScript/视窗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML文件中包含以下代码:

I have the following code in my HTML file:

    <script type="text/javascript">
        window.never = function() {
                 console.log('this function is never called');
        }
        (function(d, s, id){
            var js, srjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement(s); js.id = id;
            js.src = "this.script.does.not.exist.js";
            srjs.parentNode.insertBefore(js, srjs);
        }(document, 'script', 'streamrail-jssdk'));
    </script>

请参阅小提琴: http://jsfiddle.net/sebvaeja/

在控制台上,您会看到 window.never 函数实际上已被调用('此函数从未被调用'被写入控制台).

Looking at the console, you can see that window.never function is actually called ('this function is never called' is written to the console).

使用Chrome开发工具进行调试时,我在调用堆栈中看到调用方是闭包(第一行: http://jsfiddle.net/sebvaeja/).

When debugging this with Chrome dev tools, I see in the call stack that the caller was the closure (first line: http://jsfiddle.net/sebvaeja/).

如果我将Never函数更改为不在全局范围之内:

If I change the never function to be off the global scope:

    function never() {
             console.log('this function is never called');
    }

然后不调用它.

有人可以解释为什么调用window.never函数吗?触发电话的原因是什么?我想这与该函数在window对象上有关,但我看不出其背后的原因.

Can someone please explain why is window.never function being called? What is triggering the call? I guess it's got something to do with the function being on the window object, but I can't see the reasoning behind that.

推荐答案

函数表达式后跟括号:

 window.never = function() { ... }
 (...)

函数表达式后的换行符终止变量语句,因此对于作为函数调用的解析器:

The line break after the function expression does not terminate the variable statement, so for the parser that's a function call:

function() { ... }(...)

实际上,您在这里使用的是完全相同的技术:

In fact, you are using the very same technique here:

(function(d, s, id){
  // ...
}(document, 'script', 'streamrail-jssdk'))

这是一个函数表达式,后跟(...),它会调用该函数.

That's a function expression followed by (...) and it calls the function.

解决方案:在定义之后添加分号,您就很好了.

Solution: Add a semicolon after the definition and you are good.

如果我将never函数更改为不在全局范围内,则不会被调用.

If I change the never function to be off the global scope ... Then it is not being called.

在这种情况下,函数定义被解释为函数声明,而不是表达式.函数声明更像是一条语句,因此不能成为 CallExpression 的一部分.因此,以下括号被解释为分组运算符(如您预期的那样).

In that case the function definition is interpreted as function declaration, not expression. A function declaration is more like a statement and therefore cannot be part of a CallExpression. The following parenthesis are therefore interpreted as grouping operator (like you intended).

这篇关于为什么要调用该函数?JavaScript/视窗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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