如何实现Javascript链式调用
最近经常使用d3,突然开始对Javascript里面链式调用的原理感兴趣。于是庖丁解牛,看看d3是如何实现一个链式调用函数的。
构造函数模式和原型模式组合
构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性。组合使用构造函数模式与原型模式,每个实例都会有自己的一份实例属性的副本,但同时又共享着对方法的引用,最大限度地节省了内存。例如
var Specie = function(name, status){
this.name = name;
this.status = status;
}
Specie.prototype = {
getName: function(){
console.log(this.name);
},
getStatus: function(){
console.log(this.status);
}
}
// 实例化,调用方法
var Panda = new Specie("Giant Panda", "VU");
Panda.getName();
Panda.getStatus();
// Giant Panda
// VU
要实现链式调用是非常简单的事情,唯一需要做的就是在每个方法后面返回this
。例如:
var Specie = function(name, status){
this.name = name;
this.status = status;
}
Specie.prototype = {
getName: function(){
console.log(this.name);
return this;
},
getStatus: function(){
console.log(this.status);
return this;
}
}
// 实例化,调用方法
var Panda = new Specie("Giant Panda", "VU");
Panda.getName().getStatus();
// Giant Panda
// VU
细心一点你会发现这里Specie
实例前还需要一个new
初始化,还是有点不方便。在改进一下:
var Specie = function(name, status){
this.name = name;
this.status = status;
}
Specie.prototype = {
getName: function(){
console.log(this.name);
return this;
},
getStatus: function(){
console.log(this.status);
return this;
}
}
window.Specie = function(name, status){
return new Specie(name,status);
};
// 直接调用方法
Specie("Giant Panda", "VU").getName().getStatus();
// Giant Panda
// VU
但是这样有两个Specie
全局变量,在改进一下:
var Specie = function(name, status){
if(!(this instanceof Specie)){ // 判断this是否为Specie实例,如果不是就创建一个新实例。
return new Specie(name,status);
};
this.name = name;
this.status = status;
}
Specie.prototype = {
getName: function(){
console.log(this.name);
return this;
},
getStatus: function(){
console.log(this.status);
return this;
}
}
//直接调用方法
Specie("Giant Panda", "VU").getName().getStatus();
// Giant Panda
// VU
使用iife
模式,让代码更加安全代码:
(function () {
var Specie = function(name, status){
if(!(this instanceof Specie)){ // 判断this是否为Specie实例,如果不是就创建一个新实例。
return new Specie(name,age);
};
this.name = name;
this.status = status;
}
Specie.prototype = {
getName: function(){
console.log(this.name);
return this;
},
getStatus: function(){
console.log(this.status);
return this;
}
}
return (Window.Specie = Specie);
})()
//直接调用方法
Specie("Giant Panda", "VU").getName().getStatus();
// Giant Panda
// VU
和d3实现链式调用的思路差不多