为什么要调用该函数?JavaScript/视窗

编程入门 行业动态 更新时间:2024-10-11 17:23:08
本文介绍了为什么要调用该函数?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>

请参阅小提琴: jsfiddle/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开发工具进行调试时,我在调用堆栈中看到调用方是闭包(第一行: jsfiddle/sebvaeja/).

When debugging this with Chrome dev tools, I see in the call stack that the caller was the closure (first line: jsfiddle/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/视窗

本文发布于:2023-11-27 22:22:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639827.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视窗   函数   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!