<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#display{width: 300px;height: 300px}
</style>
</head>
<body>
<div id="app">
<p><a href="#/">home-first</a></p>
<p><a href="#/home">home</a></p>
<p><a href="#/contact">contact</a></p>
<p><a href="#/news">news</a></p>
</div>
<div id="display">
</div>
<script type="text/javascript">
function Router(){
this.paths={};
this.curPath='';
}
Router.prototype={
path:function(str,callback){
var func=callback||function(){};
this.paths[str]=func;
},
refresh:function(){
this.curPath=location.hash.slice(1)||'/home'
this.paths[this.curPath]()
},
init:function(){
window.addEventListener('load',this.refresh.bind(this),false)
window.addEventListener('hashchange',this.refresh.bind(this),false)
}
}
var display=document.getElementById('display');
var r=new Router();
r.path('/home',function(){
display.innerHTML='home';
display.style.background='yellow'
})
r.path('/contact',function(){
display.innerText='contact';
display.style.background='black'
})
r.path('/news',function(){
display.innerText='news';
display.style.background='green'
})
r.init()
</script>
</body>
</html>
- 这里的关键事load和hashchange事件,通过监测路由变化而得到内容的变化
- this.paths是存储页面内容的对象
- this.curPath是存储当前路由
bind的实现
function a(fn,context) {
var args = Array.prototype.slice.call(arguments,2)
return function() {
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs)
fn.apply(context,finalArgs)
}
}
function main() {
console.log(this.b)
}
Function.prototype.bind = function(context) {
var that = this;
var args = Array.prototype.slice.call(arguments,1)
return function() {
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs)
that.apply(context,finalArgs)
}
}
js实现多次bind
var self = null
Function.prototype.bind = function() {
if (self == null){
self = this
}
var context = [].shift.call(arguments),
args = [].slice.call(arguments);
return function() {
return self.apply(context, [].concat.call(args, [].slice.call(arguments)));
}
};