链式调用函数的核心是返回实例本身。
例如:
//示例1
class Person {
weight() {
console.log('我的体重是45kg');
return this;
},
age() {
console.log('我的年龄是18');
return this;
},
height(){
console.log('我的身高是168厘米');
return this
}
}
const I = new Person();
I.weight().age().height();
//我的体重是45kg
//我的年龄是18
//我的身高是168厘米
//示例2
function Class() {
console.log('首次')
}
Class.prototype.method = function(param) {
console.log(param)
return this
}
let one = new Class()
//由于new 在实例化的时候this会指向创建的对象, 所以this.method这个方法会在原型链中找到。
one.method('第一次调用').method('第二次链式调用').method('第三次链式调用')