向方法添加方法

时间:2013-10-29 22:59:49

标签: javascript

我希望我的代码是这样的:

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 <---
    }
}

我不知道如何在方法中添加方法add。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

这有时被称为“流畅的界面”

每个功能只需return this

如果要捕获“select”上下文,请在该范围内的变量中捕获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
}

答案 2 :(得分: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;
}

这一个的问题:http://jsfiddle.net/markasoftware/34BYa/