链式调用的核心就在于调用完的方法将自身实例返回
- 普通调用
//创建一个bird类
function Bird() {
this.startRun = function () {
console.log("开始");
}
this.stopRun = function () {
console.log("结束");
}
}
var bird = new Bird();
bird.startRun(); // 开始
bird.stopRun(); // 结束
该种方式会多次重复使用一个对象变量
- 链式调用
//创建一个bird类
function Bird() {
this.startRun = function () {
console.log("开始");
return this; // return this 返回调用当前方法的对象
}
this.stopRun = function () {
console.log("结束");
return this;
}
}
// new 在实例化的时候 this 会指向创建的对象
var bird = new Bird();
bird.startRun().stopRun(); // 开始 结束
链式调用这助于简化代码的编写工作,让代码更加简洁、易读,同时也避免多次重复使用一个对象变量
- 示例
var obj = {
a: function() {
console.log("a");
return this;
},
b: function() {
console.log("b");
return this;
},
};
obj.a().b();