用原生js实现的链式调用函数

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<input type="text" id="content">
<button type="button" id="btn">click</button>
</div>
<script>
window.onload = function(){
var oContent = document.getElementById('content');
var oBtn = document.getElementById('btn');

var SayHello = function(){
this.content = '';
};
SayHello.prototype = {
SayMorning: function(){
this.content += 'good morning';

//每次调用返回this也就是调用函数的对象
return this;
},
SayNight: function(){
this.content += 'good night';
return this;
}
}

oBtn.addEventListener('click', function(){
var sayhello = new SayHello();

//在这里地阿姨那个SayMorning之后返回了调用对象sayhello 
sayhello.SayMorning().SayNight();//这里相当于sayhello.SayMorning(),sayhello.SayNight();
oContent.value = sayhello.content;
},false);
}
</script>
</body>
</html>

posted @ 2016-10-12 10:12  故园苒苒  阅读(2401)  评论(0编辑  收藏  举报