Evg*_*eny 12 javascript jslint
JSLint不喜欢这段代码说''b'在定义之前就被使用了"
var a = function () {
b();
},
b = function () {
alert("Hello, world!");
};
a();
Run Code Online (Sandbox Code Playgroud)
但对此非常满意
var a, b;
a = function () {
b();
};
b = function () {
alert("Hello, world!");
};
a();
Run Code Online (Sandbox Code Playgroud)
但我没有在我的第二个代码片段中定义任何内容.我只是声明变量b.
那么为什么JSLint这样做呢?我有理由先宣布我的所有职能吗?
PS我明白我可以改变a和b的顺序,但在实际项目中我的函数是事件处理程序,有时它们互相调用,所以它可能是不可能的.
use*_*123 11
那么为什么JSLint这样做呢?我有理由先宣布我的所有职能吗?
是的,否则可能会出现一些意外错误.您的代码因JavaScript的"吊装"而起作用.此机制会提取隐式或显式的所有声明,并可能导致一些意外结果.
考虑以下代码:
var s = "hello"; // global variable
function foo() {
document.write(s); // writes "undefined" - not "hello"
var s = "test"; // initialize 's'
document.write(s); // writes "test"
};
foo();
Run Code Online (Sandbox Code Playgroud)
它被解释如下:
var s = "hello"; // global variable
function foo() {
var s; // Hoisting of s, the globally defined s gets hidden
document.write(s); // writes "undefined" - now you see why
s = "test"; // assignment
document.write(s); // writes "test"
}
foo();
Run Code Online (Sandbox Code Playgroud)
(例子来自德语维基百科页面:http://de.wikipedia.org/wiki/Hoisting)
归档时间: |
|
查看次数: |
6609 次 |
最近记录: |