1 关于typeof()的使用
var user;
if(typeof(user) == "undefined") {
alert("undefined");
}
上面代码会提示 undefined;
var user = null;
if(typeof(user) == "undefined") {
alert("undefined");
} else {
alert("defined");
}
这样使用则会提示 defined;
2 利用JS对象构造map
var map = {};
var key = "login";
map[key] = function(){
console.log("登录函数注册到map中");
}
alert(map[key]);
比较实用的小技巧,例如构造一个监听器对象,可以把要监听的事件(函数)注册到map中,根据key值和其他参数调用事件
实例:
function TA_EventEmitter() {
this.callbacks = {};
};
TA_EventEmitter.prototype.on = function (event, fn) {
(this.callbacks[event] = this.callbacks[event] || [])
.push(fn);
return this;
};