When creating functions on an object in Object Oriented Javascript, returning the object in the function will enable you to chain functions together.
function Person(name) {
this.name = name;
this.sayName = function() {
console.log("Hello my name is: ", this.name);
return this;
};
this.changeName = function(name) {
this.name = name;
return this;
};
}
var person = new Person("John");
person.sayName().changeName("Timmy").sayName();
from:github/loverajoel
本文介绍了一种在面向对象的JavaScript中实现方法链的方法。通过在每个方法末尾返回当前对象,可以连续调用对象上的多个方法,提高了代码的可读性和简洁性。
1432

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



