您问题中的代码不能反映正确的实现,但是要回答您的直接问题,是的,这...
UI.folders().getSelectedFolder()
...将是方法链接的一个示例。
装饰器模式是不同的。如果您有一组方法,并且每个方法都应始终首先调用某个公共函数,则可以创建一个装饰器,该装饰器将返回一个函数,该函数首先调用公共函数,然后是实际的函数......
function foo() {
console.log('I\'m foo, and I\'m first, and I was given these args:', arguments);
}
function decorateWithFoo(decorated) {
return function () {
foo.apply(this, arguments);
decorated.apply(this, arguments);
};
}
所以你可以decorateWithFoo
用来创建一个总是foo
首先调用的函数......
// create and decorate bar()
var bar = function(a,b) {
console.log('I\'m bar, and I was called after "foo", and was given args:', a, b);
};
bar = decorateWithFoo(bar);
bar(123, 456); // this will first call `foo()`, then (the original) `bar()`.
// create and decorate baz()
var baz = function(a,b) {
console.log('I\'m baz, and I was called after "foo", and was given args:', a, b);
};
baz = decorateWithFoo(baz);
baz(123, 456); // this will first call `foo()`, then (the original) `baz()`.
一些语言内置了用于创建装饰器的语法。JavaScript 目前没有。
如果您发现自己以不同的方式使用装饰器,您可以创建另一个函数来设置初始装饰器功能......
function generateDecorator(decorator) {
return function (decorated) {
return function () {
decorator.apply(this, arguments);
decorated.apply(this, arguments);
};
};
}
所以我们的原版decoreateWithFoo
可以这样设置......
function foo() {
console.log('I\'m foo, and I\'m first, and I was given these args:', arguments);
}
var decorateWithFoo = generateDecorator(foo);