1

I want my code to be like this:

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

I have only this:

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

I dont know how to add the method add in the method where.

4

3 回答 3

1

在每个函数中,输入“return this;” 在底部。因此,当您调用 .and() 时,它会在“this”上调用,即“select”。对不起,在 iPhone 上,所以没有格式化!

于 2013-10-29T23:02:12.877 回答
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
}
于 2013-10-29T23:03:33.323 回答
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/

如果您试图做到这一点and并且where在同一个对象上,请改为执行以下操作:

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/

于 2013-10-29T23:03:04.053 回答