所谓链式调用就是函数调用结束后返回当前函数运行作用域中的this对象,实现链式调用;
作为对象方法使用:
let myObj = {
name: 'geng',
age: 24,
getName: function () {
console.log(this.name);
return this;
},
getAge: function () {
console.log(this.age);
return this;
}
}
myObj.getName().getAge();
作为类的原型方法:
function Person (name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
getName: function () {
console.log(this.name);
return this;
},
getAge: function () {
console.log(this.age);
return this;
}
}
let ming = new Person('ming', 12);
ming.getName().getAge();