巧用callback实现链式调用

normall

1
2
3
4
5
6
7
8
9
10
11
12
13
window.Normal = window.Normal || function(){
var name = 'hello';
//private
this.setName = function(n){
name = n;
return this;
}
//private
this.getName = function(){ return name;}
};
var NM = new Normal;
console.log(NM.getName()); // displays 'hello'
console.log(NM.setName('world').getName());// displays 'world'

use callback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
window.Normal = window.Normal || function(){
var name = 'hello';
//private
this.setName = function(n){
name = n;
return this;
}
//private
this.getName = function(cb){
cb.call(this,name);
return this;
}
};
function log(s){ console.log(s);}
var NM = new Normal;
NM.getName(log).setName('world').getName(log); // displays 'hello' then 'world'