比如有如下的第三方代码:
- [quote]function Person(name, age) {
- this.name = name;
- this.age = age;
- this.count++;
- }
- Person.prototype = {
- sayName: function() {
- console.log(this.name);
- },
- sayAge: function() {
- console.log(this.age);
- },
- getCount: function() {
- return this.count;
- },
- count: 0
- };
- var p = new Person('xxx', 18);
- p.sayName();
- p.sayAge();
- var count = p.getCount();
- console.log(count);[/quote]
上面 Person 类明显是不支持链式调用的.
我们希望的使用方式是:
- [quote]var p = new Person('xxx', 18);
- var count = p
- .sayName()
- .sayAge()
- .getCount();
- console.log(count);[/quote]
要做到链式调用, 需要该相应的方法返回 this, 比如上面的 sayName 方法.
不改变源代码的基础上, 如何让它返回 this 呢? 添加一层包裹函数就能做到, 比如:
- [quote]var old = Person.prototype.sayName;
- Person.prototype.sayName = function() {
- var result = old.apply(this, arguments);
- return result === undefined ? this : result;
- };[/quote]
先执行原方法, 根据其返回值, 来判断该方法是否支持链式调用.
原 sayName 是没有返回值的, 因此新 sayName 变成支持链式调用的.
如果把 sayName 改成 getCount, 那么新的 getCount 跟原先做的事情是一样的, 仍不支持链式调用的, 这是我们想要的结果.
来源: http://www.qdfuns.com/article/17398/8caa2d6f9f30b3e0787334c0787ce121.html