var count = (function () {
var temp = 0
return function () {
return temp++
}
})()
console.log(count())
console.log(count())
console.log(count())
複製代碼
function fn(a) {
console.log(a)
var a = 2
function a() {
}
console.log(a)
}
fn(1)
//[Function: a]
//2
複製代碼
js中建立函數有兩種方式:函數聲明式和函數字面量式。只有函數聲明才存在函數提高!函數提高優先級高於變量提高javascript
在js中函數的聲明 比變量優先級要高 而且定義過程不會被變量覆蓋 除非是賦值java
console.log(fn) //輸出undefined
var fn = function() {}
//至關於
var fn = undefined
console.log(fn)
fn = function() {}
複製代碼
var z = 10
function foo() {
console.log(z)
}
foo();
(function () {
var z = 20
foo()
})();
(function (funArg) {
var z = 30
funArg()
})(foo)
//10
//10
//10
複製代碼
function wrapElements(a) {
var result = []
for (var i = 0, n = a.length; i< n; i++) {
result[i] = function () {
return a[i]
}
}
return result
}
var wrapped = wrapElements([10, 20, 30])
var f = wrapped[0]
console.log(f()) // undefined
複製代碼