(function () {
var variable1 = "Hello, World!" // Semicolon is missed out accidentally
var variable2 = "Testing..."; // Still a local variable
var variable3 = 42;
}());
而第二种方式就不那么宽容了:
(function () {
var variable1 = "Hello, World!" // Comma is missed out accidentally
variable2 = "Testing...", // Becomes a global variable
variable3 = 42; // A global variable as well
}());
for (var i = 0, n = a.length; i < n; i++) {
var e = a[i];
console.log(e);
}
我在JavaScript中查看了一下这个是否可以。
即使看到它工作,一个问题仍然存在n是否是函数的局部。
这将验证n是本地的:
a = [3, 5, 7, 11];
(function l () { for (var i = 0, n = a.length; i < n; i++) {
var e = a[i];
console.log(e);
}}) ();
console.log(typeof n == "undefined" ?
"as expected, n was local" : "oops, n was global");
var /* Variables */
me = this, that = scope,
temp, tempUri, tempUrl,
videoId = getQueryString()["id"],
host = location.protocol + '//' + location.host,
baseUrl = "localhost",
str = "Visit W3Schools",
n = str.search(/w3schools/i),
x = 5,
y = 6,
z = x + y
/* End Variables */;
const
x = 1,
y = 2,
z = 3
;
// or
const x=1, y=2, z=3;
// or if I'm going to pass these params to other functions/methods
const someCoordinate = {
x = 1,
y = 2,
z = 3
};
对我来说,这更符合解构:
const {x,y,z} = someCoordinate;
这样做(我不会这么做的)会感觉很笨拙。
const x = someCoordiante.x;
const y = someCoordiante.y;
const z = someCoordiante.z;