只需在方法调用后返回this即可
var user = function(name, age) {
this.name = name;
this.age = age;
};
user.prototype.getName = function() {
console.log(this.name);
return this;
};
user.prototype.getAge = function() {
console.log(this.age);
return this;
};
var user1 = new user("zjf", 22);
user1.getName().getAge();
优点:可以像jQuery一样方便书写
缺点:在调试的时候,不容易找到错误点,即不利于维护
本文介绍了一种在JavaScript中实现链式调用的方法,通过在原型方法中返回this,使得方法可以像jQuery那样连续调用。示例展示了如何在自定义的User对象中实现getName和getAge方法的链式调用。该方式虽然提高了代码的可读性和紧凑性,但在调试时可能增加难度。
1619

被折叠的 条评论
为什么被折叠?



