首页 > 代码库 > 用原生js实现的链式调用函数

用原生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 = http://www.mamicode.com/sayhello.content;
},false);
}
</script>
</body>
</html>

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