闭包的效果
function foo () {
var a = 2;
function bar () {
console.log(a);
}
return bar;
}
var baz = foo()
baz()
循环与闭包
for (var i = 0; i < 5; i++) {
(function (j) {
setTimeout(function timer () {
console.log(j);
}, j*1000)
})(i)
}
for (let i = 0; i < 5; i++) {
setTimeout(function timer () {
console.log(i);
}, i*1000)
}
模块机制
var MyModules = (function Manager() {
var modules = {};
function define(name, deps, impl) {
for (var i=0; i<deps.length; i++) {
deps[i] = modules[deps[i]];
}
modules[name] = impl.apply( impl, deps );
}
function get(name) {
return modules[name];
}
return {
define: define,
get: get
};
})();
MyModules.define( "bar", [], function() {
function hello(who) {
return "Let me introduce: " + who;
}
return {
hello: hello
};
});
MyModules.define( "foo", ["bar"], function(bar) {
var hungry = "hippo";
function awesome() {
console.log( bar.hello( hungry ).toUpperCase() );
}
return {
awesome: awesome
};
});
var bar = MyModules.get( "bar" );
var foo = MyModules.get( "foo" );
console.log(
bar.hello( "hippo" )
);
foo.awesome();
this 与 箭头函数
var obj = {
id: "awesome",
cool: function coolFn() {
console.log( this.id );
}
};
obj.cool();
var id = "not awesome"
setTimeout( obj.cool, 100 );
setTimeout(function coolFn(){
}, 100)