2013-10-29 107 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/