我们有一些Foo对象
var Foo = function() {
this.bar = function(bazinga) {
if (bazinga) {return this;}
else {return false;}
}
this.show = function() {
alert('bar');
}
};
Run Code Online (Sandbox Code Playgroud)
所以它允许我们做一些foo.bar().bar().bar().bar();链.
但是如果在链的中间,bar()将返回false,则下一个bar()尝试将导致错误,即错误undefined has no method bar().
那么如何使所有链返回false而不会出现任何"响铃"返回错误的错误?
您必须更改栏的返回类型。我建议为此目的创建一种 null 对象,并在链的末尾添加一个终结方法,该方法为 null 对象返回 false:
var Foo = function() {
var nullFoo = function() {
this.finalize = function() { return false; }
this.bar = function() { return this; }
}
this.finalize = function() { return this; }
this.bar = function(bazinga) {
if (bazinga) {return this;}
else {return new nullFoo();}
}
this.show = function() {
alert('bar');
}
};
foo.bar().bar().bar().bar().finalize();
Run Code Online (Sandbox Code Playgroud)
对于您的小提琴示例,我没有使用 Finalize 方法,而是为 null 对象提供了 show 方法。否则你false.show()最后仍然会得到:
| 归档时间: |
|
| 查看次数: |
1211 次 |
| 最近记录: |