以这些方式声明函数之间是否存在主要区别:
function foo(){
alert('BAR');
}
Run Code Online (Sandbox Code Playgroud)var foo = function (){
alert('BAR');
}
Run Code Online (Sandbox Code Playgroud)var foo = function bar(){
alert('BAR');
}
Run Code Online (Sandbox Code Playgroud)我在这里被告知:
它发生在不同的时间,并导致变量引用匿名函数.函数声明发生在作用域中执行的任何逐步代码之前,并导致绑定和具有正确名称的函数.
我声明我的函数的方式是否真的会影响我的代码的效率,如果是这样,最好使用哪种方式?
我的 HTML 文件中有以下代码:
<script src = "js/create.js"></script>
<script>
function show() {
//some code here
}
</script>
Run Code Online (Sandbox Code Playgroud)
在 JavaScript 文件 create.js 中,我想调用show()块中定义的函数,如下所示:
//File create.js
var a = show();
Run Code Online (Sandbox Code Playgroud)
那么show()文件 create.js 中的函数是否可以访问?
我有一个关于JavaScript函数的问题.
例如,请参考以下代码.
我假设'open'函数触发'success'事件函数.但是这怎么可行呢,因为'open'函数在调用'open'函数后被附加到openRequest ?
var indexedDB = window.indexedDB;
var openRequest = indexedDB.open('MyTestDB');
openRequest.onsuccess = function (response) {
alert('sucess');
};
Run Code Online (Sandbox Code Playgroud) 我正在读这本书.Javascript,道格拉斯·克罗克福德的优秀作品.书中提供了一些例子,但我无法理解这些例子在实践中的用处和方式.为简单起见,我在这里修改了代码.这里有两种方法,我可以对变量进行函数赋值.
例1:
var test= function(ex) {
alert(ex);
};
test(5);
Run Code Online (Sandbox Code Playgroud)
这会生成值为5的警报框
例2:
var test1 = function test2(ex) {
alert(ex);
};
test1(7); //this produces alert box with value of 7
test2(8)//this does not give a alert box
Run Code Online (Sandbox Code Playgroud)
我已经定义了函数test2但是将它分配给了test1.为什么我不能通过调用test2(8)直接访问test2.此外,我没有看到示例2中的任何大优势超过示例1.如果您有一些差异,其中一个是优越的,我想听到.
谢谢
我有两个类似的功能,但一个工作,另一个不工作
function notWorking(el) {
return getEventListeners(el);
}
notWorking(document);
// result --> Uncaught ReferenceError: getEventListeners is not defined
working = function(el) {
return getEventListeners(el);
}
working(document);
// result --> Object {keyup: Array[1], …}
Run Code Online (Sandbox Code Playgroud)
为什么getEventListeners在第二个函数内部工作而不在第一个函数内?
这有效:
var http = require('http');
var handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}
http.createServer(handler).listen(8080);
Run Code Online (Sandbox Code Playgroud)
但事实并非如此
var http = require('http');
http.createServer(handler).listen(8080);
var handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么因为它应该提升所有我没有错误.