用return this來串接方法,讓語法使用更簡潔
Wed, 02 Jul 2008 02:09:08 +0800因為需要寫一個陣列查詢的功能,希望用起來簡單,所以想要用類似sql語句的方式來使用,想到的作法就是在方法最後return this。 例如寫一個叫做aql的函數:
function aql() { this.select = function(a) { this.selection = a; return this; }; this.from = function(a) { this.fromArray = a; return this; }; this.where = function(a) { this.whereCriteria = a; return this; }; this.orderby = function(a) { this.order = a; return this; }; this.query = function() { if(this.selection) alert(this.selection); if(this.fromArray) alert(this.fromArray); if(this.whereCriteria) alert(this.whereCriteria); if(this.order) alert(this.order); } }
傳統的使用方式像這樣:
var a = new aql(); a.select([0,1]); a.from([[1,'abc',2334],[2,'def',84850],[3,'ghi',3884]]); a.where([0,'=',2]); a.orderby([0]); a.query();
但是使用return this的話,就可以用更簡潔的語法,好像在使用sql:
new aql().select([0,1]).from([[1,'abc',2334],[2,'def',84850],[3,'ghi',3884]]).where([0,'=',2]).orderby([0]).query();
2008-10-4 0:12 補充
前幾天在Crockford的書《Javascript: 優良部分》中看到,他把這個方法稱作Cascade。