2013-10-29 110 views
1

我想我的代碼是這樣的:添加方法的方法

select("*").where("you='me'").and("me='him'").and("game='nes'"); 

我只有這個:

function select(selector){ 
    this.where = function(where){ 
     //Do something with where and select. 
     //Add the method AND <--- 
    } 
} 

我不知道如何來添加方法的方法,其中添加。

+0

什麼好像你正在努力實現在調用'方法chaining',在這裏讀了一下:http://kwilson.me.uk/blog/simple-javascript-method-chaining/ –

回答

1

這有時被稱爲從各功能的 '連貫接口'

return this簡單。

如果你想要捕捉的「選擇」的背景下,該範圍內的變量捕獲this,然後在需要時返回。這是因爲在當前正在執行的功能this點很重要。

function select(s){ 

    var that = this; 

    this.where = function(condition){ 
     that.filter(condition); 
     return that; //this == select.where 
    } 

    this.and = function (condition) { 
     that.filter(condition); 
     return that; 
    } 

    this.end = function(){ 
     return that.results(); // or similar depending on the consumed api of course 
    } 

    return this; // this == select 
} 
+0

呀它的工作原理!我會檢查你,但我認爲這是一個不同的方法,如jQuery的,但感謝,我很感激! –

1

在每一個功能,把「迴歸本;」在底部。所以當你調用.and()時,它被稱爲「this」,這是「select」。對不起在iPhone上,所以沒有格式化!

0

一個辦法做到這一點:

function select(selector){ 
    return {where:function(where){ 
     //do whatever you're doing with where and selector 
     return {and:function(whatever){/*do something with whatever*/}} 
    }} 
} 

您可以將每個返回的對象添加額外的功能

的jsfiddle:http://jsfiddle.net/markasoftware/78aSa/1/

如果你試圖讓這個andwhere是對同一個對象,而是執行此操作:

function select(selector){ 
    var selectObj=this; 
    this.where=function(where){ 
     //do whatever with where and select 
     //now add the and method 
     selectObj.and=function(whatever){ 
      //do stuff with selector, where, and whatever 
     } 
     return selectObj 
    } 
    return selectObj; 
} 

的jsfiddle這一個:http://jsfiddle.net/markasoftware/34BYa/