0
点赞
收藏
分享

微信扫一扫

JavaScript面试题集(四)

1.简单路由器实现

var wawa = {};//这个不用解释吧
wawa.Router = function(){
	function Router(){
	}//构造器。
	Router.prototype.setup = function(routemap, defaultFunc){//基本参数路由表,默认回调。
	var that = this, rule, func;
	this.routemap = [];//路由表其实是个数组。
	this.defaultFunc = defaultFunc;
	for (var rule in routemap) {//遍历
		if (!routemap.hasOwnProperty(rule)) continue;//知识点:hasOwnProperty这个怎么用?
		that.routemap.push({
		rule: new RegExp(rule, 'i'),
		func: routemap[rule]//路由函数
	}); 
	}
};
	Router.prototype.start = function(){
	console.log(window.location.hash);//知识点:location.hash--- 监听浏览器的hash改变 ie8版本为分割点 关于onhashchange的实现(原谅我不分大小写)
	var hash = location.hash, route, matchResult;
	for (var routeIndex in this.routemap){
	route = this.routemap[routeIndex];
	matchResult = hash.match(route.rule);//知识点:match返回的是一个还是多个
	if (matchResult){
	route.func.apply(window, matchResult.slice(1));//call和apply的区别 关于改变函数this的事  slice(-1)是什么意思
	return; 
	}
	}
	this.defaultFunc();
	};
	return Router;
}();
var router = new wawa.Router();
router.setup({
'#/list/(.*)/(.*)': function(cate, id){
console.log('list', cate, id);
},
'#/show/(.*)': function(id){
console.log('show', id); 
}
}, function(){
console.log('default router');
});
router.start();
举报

相关推荐

0 条评论